如何使用C++查找数据集中的局部最大值
How to find local maximums in data set using C++?
我正在使用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;
}
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 使用的未初始化局部变量'Quick'
- 将非平凡的项目放在多集中
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 为什么 'main' 函数中的局部 int 变量会自动初始化?
- 我是否不正确地集中了这些字符数组?
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 在 OpenGL 中将笛卡尔世界坐标转换为球面局部坐标
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 离开范围后如何保护局部变量的值?
- 局部变量名称冲突
- 如何从 x64 程序集中的堆栈中获取参数?
- C++ lambda:如何'freeze'局部变量的值?
- 如何使用C++查找数据集中的局部最大值