Count the number of indices between two indices

14 次查看(过去 30 天)
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 个评论
Djdj Cjcjxj
Djdj Cjcjxj 2020-8-4
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

请先登录,再进行评论。

采纳的回答

Adam Danz
Adam Danz 2020-8-3
编辑:Adam Danz 2020-8-3
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 个评论
Rik
Rik 2020-8-4
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by