将如下matlab代码转成C语言代码 function [idx, pow] = getBestIdx(spec, low, high, num, fs, Nfft, step) % step: 指定间隔多少bpm [~, eIdx] = sort(spec(low:high), 'descend'); % 从大到小排序 eIdx = eIdx + low - 1; cnt = 1; res = zeros(1, num); pow = zeros(1, num); for k = 1 : length(eIdx) aa = (eIdx(k) - step : eIdx(k) + step); aa(aa < low) = low; aa(aa > high) = high; aa = spec(eIdx(k)) - spec(aa); if length(find(aa < 0)) == 0 res(1, cnt) = eIdx(k); pow(1, cnt) = spec(eIdx(k)); cnt = cnt + 1; if cnt > num break; end end end idx = res; pow = pow / max(pow);
时间: 2024-03-15 18:47:47 浏览: 98
以下是将Matlab代码转换为C语言代码的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void getBestIdx(double *spec, int low, int high, int num, double fs, int Nfft, int step, int *idx, double *pow) {
int i, j, k, cnt;
int *eIdx;
double *res, *aa;
// Allocate memory
eIdx = (int*) malloc((high - low + 1) * sizeof(int));
res = (double*) malloc(num * sizeof(double));
aa = (double*) malloc((2 * step + 1) * sizeof(double));
// Sort spec from high to low
for (i = 0; i <= high - low; i++) {
eIdx[i] = i + low;
}
for (i = high - low; i > 0; i--) {
for (j = 0; j < i; j++) {
if (spec[eIdx[j] - low] < spec[eIdx[j+1] - low]) {
int temp = eIdx[j];
eIdx[j] = eIdx[j+1];
eIdx[j+1] = temp;
}
}
}
// Find the best idx
cnt = 0;
for (k = 0; k <= high - low; k++) {
// Calculate aa
for (i = 0; i <= 2 * step; i++) {
int idx_aa = eIdx[k] + i - step;
if (idx_aa < low) idx_aa = low;
if (idx_aa > high) idx_aa = high;
aa[i] = spec[eIdx[k] - low] - spec[idx_aa - low];
}
// Check if aa is all non-negative
int is_non_negative = 1;
for (i = 0; i <= 2 * step; i++) {
if (aa[i] < 0) {
is_non_negative = 0;
break;
}
}
// Update res and pow if aa is all non-negative
if (is_non_negative) {
res[cnt] = eIdx[k];
pow[cnt] = spec[eIdx[k] - low];
cnt++;
if (cnt >= num) break;
}
}
// Copy res to idx and normalize pow
for (i = 0; i < cnt; i++) {
idx[i] = (int) res[i];
pow[i] = pow[i] / pow[0];
}
// Free memory
free(eIdx);
free(res);
free(aa);
}
int main() {
double spec[1000];
int low = 1, high = 100, num = 5, Nfft = 1024, step = 2;
int idx[num];
double pow[num], fs = 44100;
int i;
// Initialize spec
for (i = 0; i < 1000; i++) {
spec[i] = sin(2 * M_PI * i / 1000);
}
// Call getBestIdx
getBestIdx(spec, low, high, num, fs, Nfft, step, idx, pow);
// Print results
printf("idx: ");
for (i = 0; i < num; i++) {
printf("%d ", idx[i]);
}
printf("\n");
printf("pow: ");
for (i = 0; i < num; i++) {
printf("%f ", pow[i]);
}
printf("\n");
return 0;
}
```
需要注意的是,Matlab中的数组下标是从1开始的,而C语言中的数组下标是从0开始的,因此在将Matlab代码转换为C语言代码时,需要进行相应的修改。另外,Matlab中的sort函数是从小到大排序的,而C语言中的排序函数qsort是从小到大排序的,因此在C语言代码中需要对spec数组进行从大到小的排序。
阅读全文