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

编程入门 行业动态 更新时间:2024-10-15 02:27:19
本文介绍了查找值超过阈值的最长连续数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在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

结果与上面相同.

更多推荐

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

本文发布于:2023-11-29 20:00:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阈值   数组   最长

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!