How to Fill matrix rows with another row?

10 views (last 30 days)
Hello everyone,
I want fill the zero containing rows of this matrix with the row on top of it. For example, row (2:9) should be a copy of row one. Row (11:18), copy of row ten so on and so forth. This algorithm should be implemented till the end of (3240x9) matrix which is in the attachment.
1.843 6.97 -0.1 -0.001420 1.556600 -7.39140 2.1620 -3.3124 2.084
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
1.835 7.0751 -5.86 0.179 -0.0030 4.378 -3.37 1.476 -2.81
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

Accepted Answer

KSSV
KSSV on 27 Jun 2021
Let A be your matrix.
[m,n] = size(A) ;
for i = 1:m
if ~any(A(i,:))
A(i,:) = A(i-1,:) ;
end
end

More Answers (1)

Fawad Farooq Ashraf
Fawad Farooq Ashraf on 27 Jun 2021
Well you could find the indices of all the nonzero rows for a matrix A as
idx = find(~all(A==0,2));
and then you can replicate rows from idx(1)+1:idx(2)-1 equal to A(idx(1),:) using repmat function in matlab.
There could be a better logic for this but right now the one that's coming to my mind is something like this,
for i = 1:length(idx)-1
A(idx(i)+1:idx(i+1)-1,:) = repmat(A(idx(i),:),length(idx(i)+1:idx(i+1)-1),1);
end
A(idx(end)+1:size(A,1),:) = repmat(A(idx(end),:),length(idx(end)+1:size(A,1)),1);
You can develop your own logic but this kind of works as well.

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!