adding elements to beginning of each row
Mostrar comentarios más antiguos
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
Image Analyst
el 10 de Mzo. de 2018
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()?
Respuesta aceptada
Más respuestas (1)
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
el 10 de Mzo. de 2018
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!