Count the number of indices between two indices
9 views (last 30 days)
Show older comments
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?
Accepted Answer
Adam Danz
on 3 Aug 2020
Edited: Adam Danz
on 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 Comments
Rik
on 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.
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown 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!