How to remove data in a column below the first non-zero

Hallo
I have troubles with a matrix:
a =
0 0 0 0
0 1.00 1.00 0
1.00 1.00 1.00 1.00
1.00 1.00 1.00 1.00
I would like to get matlab to sort out the data below:
a =
0 0 0 0
0 1.00 1.00 0
1.00 0 0 1.00
0 0 0 0
Does anybody have an idea how to fix it? Kind regards Emil

1 Comment

See my answer for a much simpler and more efficient solution using just one line of code.

Sign in to comment.

 Accepted Answer

a = [ 0 0 0 0
0 1.00 1.00 0
1.00 1.00 1.00 1.00
1.00 1.00 1.00 1.00] ;
b = [ 0 0 0 0
0 1.00 1.00 0
1.00 0 0 1.00
0 0 0 0];
c = a ;
for i = 1:size(a,2)
idx = find(c(:,i)) ;
c(idx(2:end),i) = 0 ;
end

More Answers (3)

This is MATLAB, so you do not need to write ugly code using lots of loops, find, and if's as if this was a low-level language like C++. MATLAB code should be simple, efficient, and beautiful. Something like this:
>> a = [0,0,0,0;0,1,1,0;1,1,1,1;1,1,1,1]
a =
0 0 0 0
0 1 1 0
1 1 1 1
1 1 1 1
>> a(cumsum(a,1)>1) = 0
a =
0 0 0 0
0 1 1 0
1 0 0 1
0 0 0 0

2 Comments

Wow impressive! I have tried for hours - thanks :)
This works for the special case of matrix of 0 and 1, but needs a tweak for the case where the criteria is just "non-zero" which could include fractions and negative values.

Sign in to comment.

A=[0 0 0 0;0 1 1 0;1 1 1 1;1 1 1 1]
key=0;
for i=1:1:size(A,1)
key=0;
for j=1:1:size(A,1)
if(key==1)
A(j,i)=0;
end
if(A(j,i)==1 && key==0)
key=1;
end
end
end

3 Comments

@Emil van der Bijl: do not learn to use MATLAB with such pointlessly complex code. MATLAB code should be neat and beautiful, not full of ugly loops and if's as if this was C++.
See my answer for how this can be done efficiently in just one simple line of code.

Sign in to comment.

output = a .* [ones(1,size(a,2)); cumprod(a(1:end-1,:)==0)];

Community Treasure Hunt

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

Start Hunting!