1

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
  • What does the cell array contain? Post a minimal example dist and desired output Commented Feb 26, 2015 at 10:47

1 Answer 1

1

Perfect setup for bsxfun's masking capability here!

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

enter image description here

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{:}]
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! I've been looking for an excuse to learn how to use bsxfun for a while now. Thanks!
@AnnaSchumann Hey! you must!:) It's THE best tool out there to do almost anything on MATLAB!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.