A=[1 -10 4
0 -2 7
5 1 9]
I need to get
A=[1 0 -10 0 4
0 0 -2 0 7
5 0 1 0 9]
by for loop

 採用された回答

DGM
DGM 2022 年 6 月 6 日

0 投票

Don't need a loop.
A = [1 -10 4
0 -2 7
5 1 9];
B = zeros(size(A,1),2*size(A,2)-1); % allocate
B(:,1:2:end) = A % fill in nonzero columns
B = 3×5
1 0 -10 0 4 0 0 -2 0 7 5 0 1 0 9

5 件のコメント

Mako
Mako 2022 年 6 月 6 日
How to inert matrix in loop?
Mako
Mako 2022 年 6 月 6 日
And if I want to increase size 20X20?
DGM
DGM 2022 年 6 月 6 日
編集済み: DGM 2022 年 6 月 6 日
The above code doesn't depend on the size of A. A can be any 2D array.
A loop is not necessary. If you want to use a loop anyway, you can preallocate the output array and assign data columnwise.
A = [1 -10 4
0 -2 7
5 1 9];
B = zeros(size(A,1),2*size(A,2)-1); % allocate
cv = 1:2:size(B,2); % column indices of the output array
for c = 1:size(A,2)
B(:,cv(c)) = A(:,c); % fill in nonzero columns
end
B
B = 3×5
1 0 -10 0 4 0 0 -2 0 7 5 0 1 0 9
Mako
Mako 2022 年 6 月 6 日
Sorry, I may have asked the wrong question above.
If matrix size is:
A=[1 0 -10 0 4 0 1 0 -10 0 4 0
0 0 -2 0 7 0 0 0 -2 0 7 0
5 0 1 0 9 0 5 0 1 0 9 0
1 0 -10 0 4 0 1 0 -10 0 4 0
0 0 -2 0 7 0 0 0 -2 0 7 0
5 0 1 0 9 0 5 0 1 0 9 0]
DGM
DGM 2022 年 6 月 6 日
Either answer will zero-pad columns regardless of the size or contents of A.
If you're trying to describe a particular generalized relationship between input and output, you'll have to clarify with both inputs and outputs for your example.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2022 年 6 月 6 日

コメント済み:

DGM
2022 年 6 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by