How to make cells consistent in dimensions by shortening

Hi,
I have cell array P which contains something like this:
< 15x1 double > < 14x1 double > < 16x1 double > < 14x1 double >...
I'd like to concatenate all these into a single cell so I did the following:
Summary.D ={cell2mat(P)};
However, I got an error due to the inconsistent dimensions of different cells above. Since the number of rows in those cell range from 14 to 16, I could just reduce all the 14x1. However, I'm not sure how to shorten these cells. Could anyone help?
Thanks.

 Accepted Answer

This works:
P = {cell(14,1) cell(16,1)}
P{1} = rand(14,1)
P{2} = rand(16,1)
Q = [];
for k1 = 1:size(P,2)
Q = [Q; cell2mat(P(k1))];
end
Q % Display result

7 Comments

Thank you, Star Strider. This almost works but I guess it was my fault for not mentioning that Q should be 14xn (with n being the number of the original cells) and not just single column. Each original cell should be in a separate column.
Hmm, I used horzcat and the dimension error is still there.
Sorry, I must have missed that. Changed code. You don’t have to shorten any of your rows from your cell array. (I dislike discarding data.)
The loop is now:
Q = NaN(max(cell2mat(celr)),size(P,2)); % Create ‘Nan’ matrix
for k1 = 1:size(P,2)
q = cell2mat(P(k1));
Q(1:size(q,1),k1) = q;
end
Q % Display result
This saves everything, putting ‘NaN’ values in the blanks at the end of the shorter columns. It’s easy to retrieve the columns of data without the ‘NaN’ by using ~isnan. So if you want to recover the 14 rows of Q(:,1), use this syntax:
R = Q(~isnan(Q(:,1)))
If you want to shorten it to (14xn) and discard the other data, this works:
Q = Q(1:14,1:size(Q,2))
That is indeed better than discarding data, I much prefer the NaN approach. Quick question, in the first line of your revised code, what is cell2mat(celr) supposed to be? Is clr a typo?
My error in not posting all the code I changed. Sorry. Here’s the new full routine:
P = {cell(14,1) cell(16,1)}
P{1} = rand(14,1)
P{2} = rand(16,1)
[celr,celc] = cellfun(@size, P, 'UniformOutput',0)
Q = NaN(max(cell2mat(celr)),size(P,2)); % Create ‘Nan’ matrix
for k1 = 1:size(P,2)
q = cell2mat(P(k1));
Q(1:size(q,1),k1) = q;
end
Q % Display result
The ‘celr’ variable are the numbers of rows in the various cells. I use the maximum to define the row length of Q.
Thank you so much, Star Strider!

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!