Extract group of identical values from an array
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Sugyani Mahapatra
am 7 Jul. 2017
Kommentiert: Sugyani Mahapatra
am 7 Jul. 2017
I have the array
a = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1];
I want to extract the first and last index where a==1 as a group
o/p: [4 6; 12 15; 18 19];
Is there any efficient way to do this?
1 Kommentar
Adam
am 7 Jul. 2017
Bearbeitet: Adam
am 7 Jul. 2017
firstIndices = find( diff(a) == 1) + 1;
lastIndices = find( diff(a) == -1);
will give you most of what you need, but you would need to make a special case for the last index which it will not find, and obviously it is more efficient to do the diff just once, etc. Shaping the results into the format you want shouldn't be difficult.
Akzeptierte Antwort
Weitere Antworten (1)
C.J. Harris
am 7 Jul. 2017
a = [0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 0 0 1 1];
nStart = find(diff([0 a 0]) == 1);
nEnd = find(diff([0 a 0]) == -1) - 1;
nResult = [nStart' nEnd'];
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!