Cell2Mat for cells with different dimensions

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

1 件のコメント

Sara Boznik
Sara Boznik 2020 年 8 月 16 日
The idea is that you first find the longest vector, second step is that you creat matrix of all 0, so if you have n vectors and the longest vector contain m elements: A=zeros(m,n). Than you should transponse every vector to column vector. And write something like that: if exist C(i,j), A(i,j)=C(i,j).
But I don't know how to do it because I get error because of different dimension in C.
Hope that I somehow helped you.
Best of luck.

サインインしてコメントする。

 採用された回答

Star Strider
Star Strider 2020 年 8 月 16 日
編集済み: Star Strider 2020 年 8 月 16 日

5 投票

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.
.

6 件のコメント

Sara Boznik
Sara Boznik 2020 年 8 月 16 日
Yes, works fine. Elda would be thankful.
Star Strider
Star Strider 2020 年 8 月 16 日
Sara Boznik —
Thank you!
It was not exactly straightforward, and required me to experiment with it.
EldaEbrithil
EldaEbrithil 2020 年 8 月 17 日
Thank you very much Star Strider and Sara Boznik!!
Star Strider
Star Strider 2020 年 8 月 17 日
As always, my pleasure!
Megha Suswaram
Megha Suswaram 2022 年 2 月 2 日
Thank you so much~
Star Strider
Star Strider 2022 年 2 月 2 日
@Megha Suswaram — My pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

製品

リリース

R2019a

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by