如何在matlab中使用'find'来查找超过给定阈值的最长可能值序列.例如,如果我有:
X = [18 3 1 11 8 10 11 3 9 14 6 1 4 3 15 21 23 24];
Run Code Online (Sandbox Code Playgroud)
并且想要找到大于8的值,我会输入:
find(X > 8)
Run Code Online (Sandbox Code Playgroud)
但是,我想在数组中找到大于给定值的最长连续值序列.在这里,答案是:
15 21 23 24
Run Code Online (Sandbox Code Playgroud)
有没有办法在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
Run Code Online (Sandbox Code Playgroud)
diffY = 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
Run Code Online (Sandbox Code Playgroud)
用例子X和t,
result_start =
15
result_end =
18
result_values =
15 21 23 24
Run Code Online (Sandbox Code Playgroud)
regexpY = 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
Run Code Online (Sandbox Code Playgroud)
结果与上述相同.
| 归档时间: |
|
| 查看次数: |
600 次 |
| 最近记录: |