Finding first series of consecutive negative numbers in an array

3 views (last 30 days)
I am trying to find the starting index of series of first 5 consecutive negative numbers in an array.
ex:
A= [ 1 2 3 -3 -5 -6 4 -5 6 7 8 -4 -5 -6 -7 -8 -9 5 6 7 8 9 1 2 3 0 -1 -2 -3]
code should detect the starting index of first 5 negative numbers in this series.
answer: starting index is 12.
any help is appreciated.
  1 Comment
Rik
Rik on 11 May 2018
What have you tried yourself? You can split this task into several smaller parts, most of which you should be able to solve yourself. Learning to program is mostly a question of learning how to split a problem into solvable parts.
Here I would suggest you convert this vector to a binary array, describing which values are negative and which are not. Then you need to either find the run lengths, or match a pattern. The last step would be to then find the starting index. The first and the last step should be easy, for the second step, use Google and/or look into the conv function.

Sign in to comment.

Answers (2)

Guillaume
Guillaume on 11 May 2018
starts = strfind(sign(A), [-1 -1 -1 -1 -1]);
starts(1)

Andrei Bobrov
Andrei Bobrov on 11 May 2018
strfind already occupied by Guillaume. :)
t = A < 0;
out = find(sum(hankel(t(1:end-4),t(end-4:end)),2)==5,1,'first')

Community Treasure Hunt

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

Start Hunting!