How to increase the size of a matrix within for loop

10 ビュー (過去 30 日間)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2021 年 5 月 13 日
編集済み: Pooneh Shah Malekpoor 2021 年 5 月 13 日
Hello
There is a for loop in my code.
imagine i obtain value 1 after the first iteration, so it would be my first array in the matrix CM--->so CM=[1]
then in the second iteration i obtain: [1 0.214; 0.214 1] which i want to be added to the matrix CM as
CM= [1 0 0;
0 1 0.214;
0 0.214 1]
then in the third iteration i obtain: [1 0 0; 0 1 0.0013; 0 0.0013 1] , so the matrix CM should become:
CM= [1 0 0 0 0 0;
0 1 0.214 0 0 0;
0 0.214 1 0 0 0;
0 0 0 1 0 0;
0 0 0 0 1 0.0013
0 0 0 0 0.0013 0]
and so forth.
How can i formulate this? Any help is highly appreciated.

採用された回答

Steven Lord
Steven Lord 2021 年 5 月 13 日
Consider creating a cell array to store the pieces you want to be placed on the main diagonal. When you want to assemble the matrix call blkdiag, creating a comma-separated list of input arguments using the cell array.
C = {1, [1 2;2 1], [1 2 3; 2 3 1; 3 1 2]};
P = blkdiag(C{1})
P = 1
Q = blkdiag(C{1:2})
Q = 3×3
1 0 0 0 1 2 0 2 1
R = blkdiag(C{1:3})
R = 6×6
1 0 0 0 0 0 0 1 2 0 0 0 0 2 1 0 0 0 0 0 0 1 2 3 0 0 0 2 3 1 0 0 0 3 1 2
S = blkdiag(C{:})
S = 6×6
1 0 0 0 0 0 0 1 2 0 0 0 0 2 1 0 0 0 0 0 0 1 2 3 0 0 0 2 3 1 0 0 0 3 1 2
  1 件のコメント
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2021 年 5 月 13 日
編集済み: Pooneh Shah Malekpoor 2021 年 5 月 13 日
Great! Could you please tell me how can i store each of the cell arrays in the matrix C? i mean how can i ask matlab to store [ 1 2;2 1] in the second array of C, then store [1 2 3; 2 3 1; 3 1 2] in the third array and so forth?
C = {1, [1 2;2 1], [1 2 3; 2 3 1; 3 1 2]}

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by