我正在使用arduino读取一个传感器,该传感器将256个值存储到一个数组中。我试图找到局部最大值但是存储的某些值在其左侧和右侧具有重复值,导致值多次打印。是否有办法获取所有真值,意味着它们是最大值并将它们存储在另一个数组中以处理并将重复值减少到只有1个值...
OR有没有办法将最大值发送到另一个数组,其中重复值减少到1?要么 IE:
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("----------------------------------");
}
答案 0 :(得分:3)
您可以检测到&#34;局部最大值&#34;或者在单个循环中出现峰值,而无需将某些内容复制到另一个数组中。您只需忽略重复值,您只需跟踪所考虑的值当前是增加还是减少。此状态从增加切换到减少之后的每个值都是峰值:
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;
}
}