Finding first series of consecutive negative numbers in an array

3 visualizaciones (últimos 30 días)
Prasanna Venkatesh
Prasanna Venkatesh el 11 de Mayo de 2018
Respondida: Andrei Bobrov el 11 de Mayo de 2018
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 comentario
Rik
Rik el 11 de Mayo de 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.

Iniciar sesión para comentar.

Respuestas (2)

Guillaume
Guillaume el 11 de Mayo de 2018
starts = strfind(sign(A), [-1 -1 -1 -1 -1]);
starts(1)

Andrei Bobrov
Andrei Bobrov el 11 de Mayo de 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')

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by