将如下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-16 19:45:54 浏览: 48
以下是将该 Matlab 代码转换为 C 语言代码的步骤:
1. 定义函数头和输入参数
```c
void getBestIdx(double *spec, int low, int high, int num, double fs, int Nfft, int step, int *idx, double *pow);
```
2. 从大到小排序
```c
int len = high - low + 1;
int eIdx[len], idx_sort[len];
for (int i = 0; i < len; i++) {
eIdx[i] = low + i;
}
for (int i = 0; i < len; i++) {
idx_sort[i] = i;
}
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (spec[eIdx[idx_sort[i]]] < spec[eIdx[idx_sort[j]]]) {
int tmp = idx_sort[i];
idx_sort[i] = idx_sort[j];
idx_sort[j] = tmp;
}
}
}
```
3. 遍历排序后的数组,找到符合条件的元素
```c
int cnt = 0;
double res[num], pow[num];
for (int k = 0; k < len; k++) {
int aa_low = eIdx[idx_sort[k]] - step;
int aa_high = eIdx[idx_sort[k]] + step;
if (aa_low < low) {
aa_low = low;
}
if (aa_high > high) {
aa_high = high;
}
double aa[aa_high - aa_low + 1];
for (int i = 0; i < aa_high - aa_low + 1; i++) {
aa[i] = spec[eIdx[idx_sort[k]]] - spec[aa_low + i];
}
int flag = 1;
for (int i = 0; i < aa_high - aa_low + 1; i++) {
if (aa[i] < 0) {
flag = 0;
break;
}
}
if (flag) {
res[cnt] = eIdx[idx_sort[k]];
pow[cnt] = spec[eIdx[idx_sort[k]]];
cnt++;
if (cnt >= num) {
break;
}
}
}
```
4. 返回结果
```c
for (int i = 0; i < cnt; i++) {
idx[i] = res[i];
pow[i] = pow[i] / max(pow, num);
}
```
阅读全文