How do I convert a cell array with multiple values per cell into a numerical array with multiple rows?

Hi,
I have a cell array called split_newdata_mean which contains multiple cells. Each of these cells contains five values in five rows.
I am looking to create a new numerical array in which the first column contains all the values from the first row of each cell in split_newdata_mean, the second column contains all the values from the second row of the of each cell and so on.
In the end I would have a array with five columns and as many rows as there are cells in split_newdata_mean.
How would that look?
Thank you!

 Accepted Answer

The dimension of the 4th Column of your cell array is 4x1, but the rest of your cell array is 5x1.
a=load("split_newdata_mean.mat");
b=a.split_newdata_mean;
b{1,4}=[b{1,4};NaN]; % making equal dimension in the 4th column
c=[b{:}];
new_mat=c'
new_mat = 5×5
2.9473 0.7736 24.7335 -32.1028 5.4609 7.9357 15.6115 28.3915 51.8624 1.0000 38.3376 62.5463 35.4955 17.6059 35.9168 15.0732 24.9668 3.2505 -21.6557 NaN 57.9756 49.9486 53.4301 45.9361 -17.1092

2 Comments

Thank you!
I am wondering if this code would also work if split_newdata_mean would have more than five cells for example and when other cell arrays would be 4x1 instead of 5x1?
If the dimension of cell arrays are equal it's quite easy to simulate.

Sign in to comment.

More Answers (1)

n = 13;
C = cell(1,n);
for i=1:n
C{i} = rand(5,1);
end
A = cell2mat(C)
A = 5×13
0.5325 0.8308 0.1696 0.5426 0.8288 0.0943 0.0901 0.0477 0.0088 0.0633 0.7838 0.8152 0.5875 0.5602 0.1857 0.8167 0.0379 0.5943 0.2901 0.4223 0.8979 0.0115 0.7217 0.7769 0.1700 0.9170 0.4148 0.5028 0.0310 0.7531 0.5795 0.2641 0.4806 0.4078 0.3184 0.1249 0.2507 0.0434 0.0765 0.7119 0.2440 0.5009 0.3589 0.4375 0.3808 0.7980 0.3042 0.8358 0.7109 0.7234 0.0162 0.7534 0.0394 0.3821 0.4162 0.1942 0.3561 0.3732 0.5347 0.6053 0.5810 0.8286 0.0096 0.7919 0.1904
class(A)
ans = 'double'

4 Comments

Hi Thorsten,
I dont quite understand where I would substitute in split_newdata_mean to make it work for my code. Could you help?
Thanks!
C is split_newdata_mean.
So you should only need the command
A = cell2mat(split_newdata_mean)
if your explanation about split_newdata_mean is correct (cell array of size (1,n) with each element containing a column vector with 5 elements).
When I put that into the command window I get the error:
Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 75)
m{n} = cat(2,c{n,:});
Any idea why that is? I have attached the file to the original question.
Yes. Your statement
Each of these cells contains five values in five rows.
is not true.

Sign in to comment.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Asked:

on 11 Dec 2022

Commented:

on 12 Dec 2022

Community Treasure Hunt

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

Start Hunting!