Finding first series of consecutive negative numbers in an array

3 ビュー (過去 30 日間)
Prasanna Venkatesh
Prasanna Venkatesh 2018 年 5 月 11 日
回答済み: Andrei Bobrov 2018 年 5 月 11 日
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 件のコメント
Rik
Rik 2018 年 5 月 11 日
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.

サインインしてコメントする。

回答 (2 件)

Guillaume
Guillaume 2018 年 5 月 11 日
starts = strfind(sign(A), [-1 -1 -1 -1 -1]);
starts(1)

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by