Count the number of indices between two indices

15 views (last 30 days)
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?
  1 Comment
Djdj Cjcjxj
Djdj Cjcjxj on 4 Aug 2020
Is there a possibility to create a new array with the index numbers of 1 and -1 when following condition is met:
y = find(a==-1)-find(a==1)-1;
if y > 100
% add to a new array find(a==1) and (a==-1) from the 1/-1 set which has index difference of over 100
end

Sign in to comment.

Accepted Answer

Adam Danz
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
Rik on 4 Aug 2020
There are 3 segments of that calculation:
  1. find(a==-1)
  2. -find(a==1)
  3. -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.

Sign in to comment.

More Answers (0)

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!