How to convert a cell array to a compatible matrix?

I have a cell array which is filled with matrices of varying size, could you help me to convert it to matrix with filling zeros at in between columns,
in this case the matrix size is ought ot be 41x 41 of double type.

1 件のコメント

KSSV
KSSV 2021 年 7 月 16 日
Fill the empty cells with appropriate zero matrices and use Cell2mat.

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

 採用された回答

Jan
Jan 2021 年 7 月 16 日
編集済み: Jan 2021 年 7 月 16 日

1 投票

CC = {rand(9,9), rand(5,4), rand(5,4), rand(6,4), rand(6,4), rand(8,4), rand(8,4), rand(9,4), rand(9, 4); ...
rand(4,5), rand(4,4), [], [], [], [], [], [], []; ...
[], [], rand(4,4), [], [], [], [], [], []; ...
rand(4,6), [], [], rand(4,4), [], [], [], [], []; ...
[], [], [], [], rand(4,4), [], [], [], []; ...
rand(4,6), [], [], [], [], rand(4,4), [], [], []; ...
[], [], [], [], [], [], rand(4,4), [], []; ...
rand(4,6), [], [], [], [], [], [], rand(4,4), []; ...
[], [], [], [], [], [], [], [], rand(4,4)};
C = CC;
S1 = cellfun('size', C, 1);
maxS1 = max(S1, [], 2);
S2 = cellfun('size', C, 2);
maxS2 = max(S2, [], 1);
for i2 = 1:size(C, 2)
for i1 = 1:size(C, 1)
X = C{i1, i2};
if size(X, 1) < maxS1(i1) || size(X, 2) < maxS2(i2)
X(maxS1(i1), maxS2(i2)) = 0;
C{i1, i2} = X;
end
end
end
Result = cell2mat(C);
Cheaper:
C = CC;
S1 = cellfun('size', C, 1);
maxS1 = max(S1, [], 2);
S2 = cellfun('size', C, 2);
maxS2 = max(S2, [], 1);
Result2 = zeros(sum(maxS1), sum(maxS2));
c1 = 1;
for i1 = 1:size(C, 1)
c2 = 1;
for i2 = 1:size(C, 2)
X = C{i1, i2};
Result2(c1:c1 + size(X,1) - 1, c2:c2 + size(X,2) - 1) = X;
c2 = c2 + maxS2(i2);
end
c1 = c1 + maxS1(i1);
end
isequal(Result, Result2)
ans = logical
1
It took some tome to create some test data as input. Please care for providing some code, which creates your input data, to make answering as easy as possible.

3 件のコメント

Nandha Kumar
Nandha Kumar 2021 年 7 月 17 日
編集済み: Nandha Kumar 2021 年 7 月 17 日
I was pretty occupied with sorting it out myself sir, and this is my first question and I never thought it would be answered sir, that has been the experience with other forum questions of mine so far, so it slipped my mind.
Aplogies for the inconvenience caused.
Thank you so much sir, for the time, effort and the knowledge sharing sir,
Thanks
P.S: I m decently good with use of arrays and linear algebra, but when something of this sort comes up, I m stumped,. is there any book or course you would suggest sir, for learning to use cells, and other hidden gems of MATLAB, which might be quite useful? If so kindly suggest, thanks
Nandha Kumar
Nandha Kumar 2021 年 7 月 17 日
@Image Analyst Thank you sir, I ll learn from it.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2015b

質問済み:

2021 年 7 月 16 日

コメント済み:

2021 年 7 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by