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 comentario

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

Iniciar sesión para comentar.

 Respuesta aceptada

Akira Agata
Akira Agata el 10 de Mzo. de 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 comentario

Lucas Chae
Lucas Chae el 10 de Mzo. de 2018
This is precisely what I needed! Thank you so much.

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 10 de Mzo. de 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 comentario

Lucas Chae
Lucas Chae el 10 de Mzo. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 10 de Mzo. de 2018

Comentada:

el 10 de Mzo. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by