如何使用C++查找数据集中的局部最大值

How to find local maximums in data set using C++?

本文关键字:集中 局部 最大值 数据集 数据 何使用 C++ 查找      更新时间:2023-10-16

我正在使用arduino读取一个传感器,该传感器将256个值存储到数组中。我正在尝试查找本地最大值,但存储的某些值在自身的左侧和右侧具有重复值,导致该值多次打印。有没有办法获取所有真实值,这意味着它们是最大值并将它们存储在另一个数组中以处理并将重复值减少到仅 1 个值......

或者有没有办法将最大值发送到另一个数组,其中重复的值减少到只有 1?或即:

Array1[] = {1,2,3,4,4,4,3,2,7,8,9,10}
max = 4 at index 3
max = 4 at index 4
max = 4 at index 5

由于 4 是一个峰值点,但重复如何减少它以使数组看起来像

Array2[] = {1,2,3,4,3,2,7,8,9,10}
max = 4 at index 3

如果可能的话,我需要最基本的细分,没有专家级别的细分,谢谢。

来自 Arduino 的代码:

int inp[20] = {24,100,13,155,154,157,156,140,14,175,158,102,169,160,190,100,200,164,143,20};
void setup()
{
  Serial.begin(9600);  // for debugging  
}
void loop()
{
    int i;
    int count = 0;
    for (i = 0; i < 20; i++)
    {
       Serial.println((String)inp[i]+" index at - "+i);
       delay(100);
    };   
 int N = 5;   // loc max neighborhood size
 for (int i = N-1; i < 19-N; i++) 
  {
      bool loc = false;
      for (int j = 1; j < N; j++) // look N-1 back and N-1 ahead
      { 
        if (inp[i] > inp[i-j] && inp[i] > inp[i+j]) loc = true;
      }
        if (loc == true)
        {         
          Serial.println((String)"max = "inp[i]+" at index "+i);
        }
     }
  Serial.println("----------------------------------");
}

您可以在单个循环中检测"局部最大值"或峰值,而无需将某些内容复制到另一个数组中。您只需要忽略重复值,并且只需要跟踪所考虑的值当前是增加还是减少。在此状态从增加切换到减少之后的每个值都是一个峰值:

int main() {
    int Array1[] = {1,2,3,4,4,4,3,2,7,8,9,10};
    int prevVal = INT_MIN;
    enum {
        Ascending,
        Descending
    } direction = Ascending;
    for (int i=0; i<sizeof(Array1)/sizeof(*Array1); i++) {
        int curVal = Array1[i];
        if (prevVal < curVal) {  // (still) ascending?
            direction = Ascending;
        }
        else if (prevVal > curVal) { // (still) descending?
            if (direction != Descending) { // starts descending?
                cout << "peak at index " << i-1 << ": " << prevVal << endl;
                direction = Descending;
            }
        }
        // prevVal == curVal is simply ignored...
        prevVal = curVal;
    }
}