Adding 0's to cell array such that each column contains an equal number of entries - MATLAB

纵然是瞬间 提交于 2019-12-11 07:17:22

问题


I have a 16x100 (varies in size) cell array and I would like to extract each of it's columns into a column of a matrix. When each column of the cell array contains an identical number of entries I can use:

elem = numel([dist{:,1}]);
repeat = size(dist,2);
data = zeros(elem,repeat);  
for k=1:repeat
  results(:,k) = [dist{:,k}]';
end

However there are some instances where there are not an equal number thus it returns the error:

Subscripted assignment dimension mismatch.

What is the best way around this? Is there a way to add zeroes to equalise the number of entries?


回答1:


Perfect setup for bsxfun's masking capability here!

Now, I am assuming your data is setup as described in your previous question -

To solve the case of filling up "empty spaces" with zeros, you can setup an output array with maximum possible number of elements in each column and then fillup the valid spaces with the values from the input cell array, with the valid spaces being detected by the logical mask created with bsxfun. Read on through the comments inlined within the code listed next to find out the exact ideas on solving it -

%// Get the number of elements in each column of the input cell array
lens = sum(cellfun('length',a),1)

%// Store the maximum number of elements possible in any column of output array
max_lens = max(lens)  

%// Setup output array, with no. of rows as max number of elements in each column
%// and no. of columns would be same as the no. of columns in input cell array 
results = zeros(max_lens,numel(lens))

%// Create as mask that has ones to the "extent" of number of elements in
%// each column of the input cell array using the lengths
mask = bsxfun(@le,[1:max_lens]',lens)  %//'

%// Finally, store the values from input cell array into masked positions
results(mask) = [a{:}]


来源:https://stackoverflow.com/questions/28739263/adding-0s-to-cell-array-such-that-each-column-contains-an-equal-number-of-entri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!