How to remove data in a column below the first non-zero
Show older comments
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
Accepted Answer
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
Emil van der Bijl
on 24 Oct 2017
Walter Roberson
on 24 Oct 2017
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.
Birdman
on 24 Oct 2017
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
on 24 Oct 2017
@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.
Birdman
on 24 Oct 2017
Thanks Stephen :))
Walter Roberson
on 24 Oct 2017
output = a .* [ones(1,size(a,2)); cumprod(a(1:end-1,:)==0)];
Categories
Find more on Logical 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!