Count the number of indices between two indices
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Djdj Cjcjxj
am 3 Aug. 2020
Kommentiert: Djdj Cjcjxj
am 4 Aug. 2020
I have an array B with 1s, -1s and 0s. Such as:
[ 0 0 0 0 0 1 0 0 0 -1 0 0 0 1 -1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 ]
I would like to count the number of indices there between each 1 and -1
result should be: 3 0 8
num = B(index_of_1 : index_of_-1);
Since the index changes constanly, I am stuck on how to write the B( : ) part. Anybody have an idea?
Akzeptierte Antwort
Adam Danz
am 3 Aug. 2020
Bearbeitet: Adam Danz
am 3 Aug. 2020
If and only if the following rules are met, the solution is very simple.
- For every "1" there will be a "-1" and for every "-1" there will be a "1"
- a "1" will always preceed a "-1"
- a "-1" will always come after a "1"
y = find(a==-1)-find(a==1)-1;
Examples where this will not work
- [ -1 0 0 1 0 0 -1]
- [0 1 -1 -1 0 1 0 -1]
- [0 0 0 1 0 0]
2 Kommentare
Rik
am 4 Aug. 2020
There are 3 segments of that calculation:
- find(a==-1)
- -find(a==1)
- -1
Lets consider a tiny example: a=[0 1 -1];
The first find returns a 3, the second returns 2. How many elements are between 2 and 3? 0. Because you want the distance between the positions, you need to subtract 1.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Startup and Shutdown 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!