简体   繁体   中英

find longest continuous array with values exceeding a threshold

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];

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

Is there a way to achieve this in matlab?

Let your data be defined as

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

Approach 1: using 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

with the example X and t ,

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

Approach 2: using 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

The result is the same as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM