how to fill with the last non empty value across each column

Hi all, how can I fill the cells in each row with the last non empty or non zero value please? For example : the matrix is [0 9 7 0 0 ; 0 0 0 6 0;0 2 0 0 0; 8 0 4 2 0]; The result shows b=[09700;09760;02760;82420]. Any help is welcomed. Thank you very much.

 Accepted Answer

A = [0 9 7 0 0 ; 0 0 0 6 0;0 2 0 0 0; 8 0 4 2 0]
B = A;
for k = 2:size(B,1)
idx = B(k,:)==0;
B(k,idx) = B(k-1,idx);
end
Produces this output:
>> A
A =
0 9 7 0 0
0 0 0 6 0
0 2 0 0 0
8 0 4 2 0
>> B
B =
0 9 7 0 0
0 9 7 6 0
0 2 7 6 0
8 2 4 2 0

3 Comments

Hi, thank you for you answer. It perfectly solved my problem. Can I go on with another question? In the A matrix, how to carry over the last nonempty value until the last nonzero value in each column. So you in second column in A, 2 is the last nonzero value in column 2, so in next round it does not carry over the 2 from the last row. So the output in B should show B(4,2)=0 rather than 2. Thank you again.
Run this new code afterwards
idy = true;
for k2 = k:-1:1
idy = idy & A(k2,:)==0;
B(k,idy) = 0;
end
to get this:
>> B
B =
0 9 7 0 0
0 9 7 6 0
0 2 7 6 0
8 0 4 2 0

Sign in to comment.

More Answers (0)

Categories

Asked:

on 30 Oct 2015

Commented:

on 1 Nov 2015

Community Treasure Hunt

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

Start Hunting!