找到值超过阈值的最长连续数组

时间:2015-09-07 13:23:12

标签: arrays matlab

如何在matlab中使用'find'来查找超过给定阈值的最长可能值序列。例如,如果我有:

X = [18 3 1 11 8 10 11 3 9 14 6 1 4 3 15 21 23 24];

并希望找到大于8的值,我会输入:

find(X > 8)

但是,我想找到数组中最大的连续值序列大于给定值的位置。在这里,答案是:

15 21 23 24

有没有办法在matlab中实现这个目标?

1 个答案:

答案 0 :(得分:8)

将您的数据定义为

X = [18 3 1 11 8 10 11 3 9 14 6 1 4 3 15 21 23 24]; %// input array
t = 8; %// threshold

方法1:使用diff

Y = X>t; %// convert to zeros and ones
z = diff([false Y false]); %// compute changes. `false`s are needed to "close" the sequence
s = find(z>0); %// find indices of starts of runs
e = find(z<0)-1; %// find ends 
[~, w] = max(e-s); %// w is the index of the longest run
result_start = s(w); %// index of start of longest subsequence
result_end = e(w); %// index of end of longest subsequence
result_values = X(s(w):e(w)); %// values of longest subsequence

示例Xt

result_start =
    15
result_end =
    18
result_values =
    15    21    23    24

方法2:使用regexp

Y = char(double(X>t) + '0'); %// convert to string of zeros and ones
[s, e] = regexp(Y, '1+', 'start', 'end'); %// find starts and ends of runs
[~, w] = max(e-s); %// w is the index of the longest run
result_start = s(w); %// index of start of longest subsequence
result_end = e(w); %// index of end of longest subsequence
result_values = X(s(w):e(w)); %// values of longest subsequence

结果与上述相同。