MATLAB: Cell2Mat for cells with different dimensions

cell2matMATLAB

Hi all
i have a cell array like this: C={(21 24 47 89 57)' , ( 24 21)' , (16 87 47 89 90 99 182)'} i want to obtain a matrix like that:
21 24 16
24 21 87
A= 47 0 47
89 0 89
57 0 90
0 0 99
0 0 182
How can i do that?
Thank you for the help
Regards

Best Answer

Try this:
C={[21 24 47 89 57]' , [24 21]' , [16 87 47 89 90 99 182]'};
rows = cellfun(@numel,C);
cols = size(C,2);
A = zeros(max(rows),cols);
for k = 1:cols
A(1:rows(k),k) = C{k};
end
producing:
A
A =
21 24 16
24 21 87
47 0 47
89 0 89
57 0 90
0 0 99
0 0 182
EDIT — (16 Aug 2020 at 21:31)
Corrected the preallocation of ‘A’ to use the previously calculated values of ‘rows’ and ‘cols’. Code otherwise unchanged.
.