Azzera filtri
Azzera filtri

Length's of matrix rows exclusing padding

4 visualizzazioni (ultimi 30 giorni)
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 :-)

Risposta accettata

Akira Agata
Akira Agata il 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 Commento
Nick Keepfer
Nick Keepfer il 2 Mar 2018
Wow, lightning fast answer!
Works perfectly, thank you very much Akira, you're awesome!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by