在一维数组中查找时间序列数据中的波峰和波谷-Javascript [英] Finding peaks and troughs in time series data in a 1D array - Javascript
问题描述
因此,基本上我有一个一维数组,其中有500多个值在100-130范围之间浮动,或以不特定的顺序排列(随机);我想知道如何找到这些数据的波峰和波谷.有没有办法改变峰值检测的灵敏度?什么是综合算法?如果有一个JS库,那就太好了.
So basically i have a 1d array with over 500 values floating between the ranges of 100- 130 or about there arranged in no particular order(its random); and I wanna know how can I find the peaks and troughs of this data. Is there a way to also change sensitivity of the peak detection? What is a comprehensive algorithm for this? If there is a JS library for it, that would be awesome.
推荐答案
查找峰和谷的算法与在查看图形时用手指进行的操作本质上是相同的.您从头开始,沿直线行驶,并在看到高峰和低谷时记录下来.
An algorithm for finding peaks and troughs would be essentially the same thing you would do with your finger when looking at a graph. You go from the start and follow the line and take note when you see a peak and a trough.
我们可以通过编程将其定义为:
Programmically we can define that as this:
对于某些长度为 n
的数组(,其中 n-1
为最后一个元素的索引,而 0
为第一个),从 1
迭代到 n-2
.然后将波峰和波谷定义为:
For some array of length n
(with n-1
being the index of the last element and 0
the index of the first), iterate thorough from 1
to n-2
. Then peaks and troughs would be defined as:
- 对于元素
i
,如果i-1>i
和i + 1>我
.那么i
是一个低谷. - 对于元素
i
,如果i-1<i
和i + 1<我
.那么i
是一个峰值.
- For element
i
, ifi-1 > i
andi+1 > i
. Theni
is a trough. - For element
i
, ifi-1 < i
andi+1 < i
. Theni
is a peak.
这将是一种 O(n)
算法,并且有足够的信息可以对其进行编程.
This would be an O(n)
algorithm and be enough information to be able to program it.
下面是实现上述algothim的示例程序:
Below is an example program implementing the algothim above:
var array = [102,112,115,120,119,102,101,100,103,105,110,109,105,100];
function findPeaksAndTroughs(array) {
var start = 1; // Starting index to search
var end = array.length - 2; // Last index to search
var obj = { peaks: [], troughs: [] };// Object to store the indexs of peaks/thoughs
for(var i = start; i<=end; i++)
{
var current = array[i];
var last = array[i-1];
var next = array[i+1];
if(current > next && current > last)
obj.peaks.push(i);
else if(current < next && current < last)
obj.troughs.push(i);
}
return obj;
}
console.log(findPeaksAndTroughs(array));
这篇关于在一维数组中查找时间序列数据中的波峰和波谷-Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!