How to find first zero element per row in a matrix and set other elements to zero without loops
Show older comments
Hi. I have a matrix of this form:
A = [ 1 2 3 0 4 5 0 0 1 1 1; 2 5 0 0 0 1 1 0 4 2 3; 4 5 2 3 0 1 2 3 4 5 6];
and i want for each line, starting from the first zero to get this type of matrix
B = [ 1 2 3 0 0 0 0 0 0 0 0; 2 5 0 0 0 0 0 0 0 0 0; 4 5 2 3 0 0 0 0 0 0 0];
I managed to get the index of each column where the first zero can be found, ie [4 3 5] but I cannot get the B matrix. Help will be greatly appreciated. Thanks!
Answers (2)
Andrei Bobrov
on 27 Mar 2015
Edited: Andrei Bobrov
on 27 Mar 2015
B = A.*(cumsum(A==0,2)==0);
Categories
Find more on Matrix Indexing 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!