フィルターのクリア

Find the longest sequence of consecutive non-zero values in a vector

19 ビュー (過去 30 日間)
kortas manel
kortas manel 2018 年 6 月 7 日
コメント済み: Walter Roberson 2018 年 6 月 7 日
Hello everyone, I want to know how to find in a vector the longest sequence of consecutive non-zero values. example: I have x = [0 1 2 3 0 5 6 7 8 0 10]; I must have as output the block y = [5 6 7 8] Thank you in advance.

採用された回答

Walter Roberson
Walter Roberson 2018 年 6 月 7 日
x = [0 1 2 3 0 5 6 7 8 0 10];
zpos = find(~[0 x 0]);
[~, grpidx] = max(diff(zpos));
y = x(zpos(grpidx):zpos(grpidx+1)-2);
  2 件のコメント
Jan
Jan 2018 年 6 月 7 日
+1. This shorter than the approach with RunLength.
Walter Roberson
Walter Roberson 2018 年 6 月 7 日
Note: the 0 before and after x in [0 x 0] are there in case the input, x, does not begin with a 0, or does not end with a 0. There are implied markers of beginning of sequence at the beginning of x and of end of sequence at the end of x.

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

その他の回答 (1 件)

Adam
Adam 2018 年 6 月 7 日
or other similar run length functions should help, especially if you trivially binarise your input first.
  1 件のコメント
Jan
Jan 2018 年 6 月 7 日
x = [0 1 2 3 0 5 6 7 8 0 10];
[b, n, xIdx] = RunLength(x ~= 0);
xIdx = xIdx(b);
[maxN, nIdx] = max(n(b));
r = x(xIdx(nIdx):xIdx(nIdx) + maxN - 1)
I think, Walter's solution is nicer.

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

Community Treasure Hunt

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

Start Hunting!

Translated by