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 Comment

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

Sign in to comment.

 Accepted Answer

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 Comment

This is precisely what I needed! Thank you so much.

Sign in to comment.

More Answers (1)

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 Comment

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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!