adding elements to beginning of each row

I have a 3x4 array that looks like this [1,2,3,4; 5,6,7,8; 9,10,11,12]. I want to add n number of zeros (n being the row number), so that it looks like this [0,1,2,3,4,0,0; 0,0,1,2,3,4,0; 0,0,0,1,2,3,4] Is there any way to achieve this in Matlab? rows and arrays work quite differently from my programming knowledge so I'm having a little difficulty.

1 件のコメント

Image Analyst
Image Analyst 2018 年 3 月 10 日
So
m1 = [1,2,3,4; 5,6,7,8; 9,10,11,12] % Input
m2 = [0,1,2,3,4,0,0; 0,0,1,2,3,4,0; 0,0,0,1,2,3,4] % Desired output
gives
m1 =
1 2 3 4
5 6 7 8
9 10 11 12
m2 =
0 1 2 3 4 0 0
0 0 1 2 3 4 0
0 0 0 1 2 3 4
What rule are you giving for transferring some (but not all) of the elements from m1 to m2?
Have you considered circshift()?

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

 採用された回答

Akira Agata
Akira Agata 2018 年 3 月 10 日

1 投票

I think the desired result could be the following.
0 1 2 3 4 0 0
0 0 5 6 7 8 0
0 0 0 9 10 11 12
Assuming this, the solution would be like this.
A = [1,2,3,4; 5,6,7,8; 9,10,11,12];
A1 = [A,zeros(3)];
B = splitapply(@(x,d) circshift(x,d), A1, (1:3)', (1:3)');

1 件のコメント

Lucas Chae
Lucas Chae 2018 年 3 月 10 日
This is precisely what I needed! Thank you so much.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2018 年 3 月 10 日

0 投票

Here's one way:
m1 = [1,2,3,4; 5,6,7,8; 9,10,11,12]
% m2 = [0,1,2,3,4,0,0; 0,0,1,2,3,4,0; 0,0,0,1,2,3,4]
rowOne = [0, m1(1,:), zeros(1, size(m1, 2)-2)]
m2 = repmat(rowOne, [size(m1, 1), 1])
for row = 1 : size(m2, 1)
thisRow = m2(row, :)
m2(row,:) = circshift(thisRow, row-1);
end
m2 % Show in command window.
It gives
m2 =
0 1 2 3 4 0 0
0 0 1 2 3 4 0
0 0 0 1 2 3 4
just like you requested.

1 件のコメント

Lucas Chae
Lucas Chae 2018 年 3 月 10 日
I had an error in my question, and I didn't need the modulus operator (and yet you figured out a way!). After that, your method works perfectly too, so thank you.

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

カテゴリ

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

タグ

質問済み:

2018 年 3 月 10 日

コメント済み:

2018 年 3 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by