How can I copy one row to the another row?

18 views (last 30 days)
I have an array like A below
A = [5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4]
I would like to do the following operaton :
every row shuld start from 0. So, for the first row discard all the values before 0 and append 5 6 7 8 9 from the next row and continue. Thus last row should have only
0 1 2 3 4 (padding rest of the position with 0). The new A should be like following
A = [ 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 0 0 0 0 0]
What is the efficinet way to do that? Thanks in advance.
  2 Comments
the cyclist
the cyclist on 13 Apr 2021
Edited: the cyclist on 13 Apr 2021
How general is the example here? For example, ...
  • Will the zeros always be aligned in a column?
  • Could there be more than one columns of zeros?
  • Could there be zeros scattered all around?
  • Could there be more than one zero in a single row?
Please try to give a very general example of input and output.
Sanjib Sarkar
Sanjib Sarkar on 13 Apr 2021
Edited: Sanjib Sarkar on 13 Apr 2021
Each row should start with 0.
Each row corresponds to a each state and ecah state has 0 to 10 values.
Thus
row1 (state 1) should have 0 1 2 3 4 5 6 7 8 9
row2 (state2) should have 0 1 2 3 4 5 6 7 8 9
.
.
  • Will the zeros always be aligned in a column? Yes
  • Could there be more than one columns of zeros? No
  • Could there be zeros scattered all around? NO
  • Could there be more than one zero in a single row? No
Actually I have to cut and paste some values from the next row to the previous row.
Thanks!

Sign in to comment.

Accepted Answer

Jan
Jan on 13 Apr 2021
Edited: Jan on 14 Apr 2021
A = [5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4;
5 6 7 8 9 0 1 2 3 4];
% Find the first 0, transpose to row-wise operation:
At = A.';
k = find(At == 0, 1, 'first');
% Crop before 1st zero and pad with zeros:
B = [At(k:end), zeros(1, k-1)];
% Transpose and reshape B to the original size:
B = reshape(B, size(At)).'

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!