Clear Filters
Clear Filters

Length's of matrix rows exclusing padding

4 views (last 30 days)
Hi, I have a matrix which looks a little like
X = [ 0 1 0 1 0 1 1 0 ]
[ 0 1 0 1 1 1 0 0 ]
[ 0 1 1 1 1 0 0 0 ]
This matrix has hundreds of rows so I cant do this manually but I wish to find the length of each vector in the array between the first 1 and the last 1 in each row
In this example it would be :
Y = [ 6 ]
[ 5 ]
[ 4 ]
Can somebody suggest how to do this.
Please note that I have simplified this problem and the numbers I have are not actually all 1's but vary between 1-10 ish.
Thanks :-)

Accepted Answer

Akira Agata
Akira Agata on 2 Mar 2018
If each row in X has at least one non-zero value, the following code can calculate Y.
X = [ 0 1 0 1 0 1 1 0;...
0 1 0 1 1 1 0 0;...
0 1 1 1 1 0 0 0 ];
[r,c] = find(X);
Y = splitapply(@(x) max(x)-min(x)+1, c, r);
  1 Comment
Nick Keepfer
Nick Keepfer on 2 Mar 2018
Wow, lightning fast answer!
Works perfectly, thank you very much Akira, you're awesome!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!