Count the number of indices between two indices

11 Ansichten (letzte 30 Tage)
Djdj Cjcjxj
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?
  1 Kommentar
Djdj Cjcjxj
Djdj Cjcjxj am 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
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
Rik am 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.
Djdj Cjcjxj
Djdj Cjcjxj am 4 Aug. 2020
Thank you @Rik for that explanation!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

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!

Translated by