- 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?
How can I copy one row to the another row?
18 views (last 30 days)
Show older comments
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
on 13 Apr 2021
Edited: the cyclist
on 13 Apr 2021
How general is the example here? For example, ...
Please try to give a very general example of input and output.
Accepted Answer
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)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!