波峰波谷检测算法 C代码软件包
时间: 2023-10-12 11:05:14 浏览: 88
寻找波峰和波谷的程序
以下是一个简单的波峰波谷检测算法的C代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MIN_PEAK_HEIGHT 5 // 定义波峰最小高度
int find_peaks(int data[], int len, int peaks[], int valleys[]) {
int i = 0;
int peak_count = 0;
int valley_count = 0;
int peak_found = 0;
int valley_found = 0;
int last_valley = 0;
int last_peak = 0;
for (i = 1; i < len - 1; i++) {
if (data[i] > data[i - 1] && data[i] > data[i + 1]) {
if (data[i] > MIN_PEAK_HEIGHT) {
peaks[peak_count] = i;
peak_count++;
peak_found = 1;
}
} else if (data[i] < data[i - 1] && data[i] < data[i + 1]) {
valleys[valley_count] = i;
valley_count++;
valley_found = 1;
if (peak_found && valley_found) {
if (valleys[valley_count - 1] > peaks[peak_count - 1]) {
last_valley = valleys[valley_count - 1];
last_peak = peaks[peak_count - 1];
peak_found = 0;
valley_found = 0;
} else {
valley_count--;
}
}
}
}
if (peak_count > valley_count) {
peaks[peak_count - 1] = last_peak;
peak_count--;
} else if (valley_count > peak_count) {
valleys[valley_count - 1] = last_valley;
valley_count--;
}
return peak_count;
}
int main() {
int data[] = {1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1};
int len = sizeof(data) / sizeof(int);
int peaks[len];
int valleys[len];
int peak_count = find_peaks(data, len, peaks, valleys);
printf("Peaks: ");
for (int i = 0; i < peak_count; i++) {
printf("%d ", peaks[i]);
}
printf("\n");
return 0;
}
```
该算法中的 `find_peaks` 函数将输入数据中的所有波峰和波谷的位置存储在 `peaks` 和 `valleys` 数组中,并返回波峰的数量。在示例代码中,我们使用一个简单的数据集来测试该算法。请注意,该算法只检测波峰的高度大于 `MIN_PEAK_HEIGHT` 的峰值。您可以根据需要调整此值。
要使用此代码,请将其保存到 `.c` 文件中并使用 C 编译器编译。例如,在Linux系统上,您可以使用以下命令编译代码:
```
gcc -o peak_detection peak_detection.c
```
然后运行生成的可执行文件:
```
./peak_detection
```
该程序将输出找到的波峰的位置。
阅读全文