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 commentaire

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()?

Connectez-vous pour commenter.

 Réponse acceptée

Akira Agata
Akira Agata le 10 Mar 2018
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 commentaire

Lucas Chae
Lucas Chae le 10 Mar 2018
This is precisely what I needed! Thank you so much.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 10 Mar 2018
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 commentaire

Lucas Chae
Lucas Chae le 10 Mar 2018
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by