查找值超过阈值的最长连续数组 [英] find longest continuous array with values exceeding a threshold
本文介绍了查找值超过阈值的最长连续数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在matlab中使用查找"来查找超过给定阈值的最长的序列值.例如,如果我有:
How can I use 'find' in matlab to find the longest possible sequence of values that exceed a given threshold. Fro example, if I have:
X = [18 3 1 11 8 10 11 3 9 14 6 1 4 3 15 21 23 24];
并要查找大于例如8的值,请输入:
and want to find the values that are larger than, say, 8, I would type:
find(X > 8)
但是,我想找出数组中最长的连续序列大于给定值的位置.在这里,答案将是:
However, I want to find where in the array is the longest continuous sequence of values larger than a given value. Here, the answer would be:
15 21 23 24
有没有办法在Matlab中实现这一目标?
Is there a way to achieve this in matlab?
推荐答案
让您的数据定义为
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
以示例X
和t
,
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
结果与上面相同.
这篇关于查找值超过阈值的最长连续数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文