我真的很难从数组中找到加权和。 我有一个名为 frequency[28] 的数组(一维大小为 28)和名为 peak[28] 的相同大小的相同索引数组。数组将始终具有值或零。我想要实现的是遍历数组,从频率和幅度数组中检索两个值,同时忽略零。此外,我并没有试图找到整个数组的加权平均值。
我觉得我说得不够清楚。
比如说
frequency[n] = [0,0,0, a,b, 0,0,0, c,d,e, 0,0, f]
peak[n] = [0,0,0, z,y, 0,0,0, x,w,v, 0,0, u]
因此,我想忽略前三个 bin,因为它们为零,并找到 (a,b) 与 (z,y) 配对的加权平均值并忽略接下来的三个 bin,然后再次找到 (c,d, e) 与 (x,w,v) 等配对。
请注意,我在数组中的值(大小是固定的)不是固定的。值可能出现的索引总是变化的。
我附上了检索数组的代码片段。 任何建议或指导都会有很大帮助!
// peak search
threshold = 0;
for (ctr=0; ctr<n1; ctr++)
{
peak[ctr] = 0; // initialise arrays
freq_bin[ctr] =0;
frequency[ctr] = 0;
// magnitude calculation from fft output
fft_mag[ctr] = 10*(sqrt((fft_output[ctr].r * fft_output[ctr].r) + (fft_output[ctr].i * fft_output[ctr].i)))/(n);
threshold = 12;
if (fft_mag[ctr] >= threshold) // extract fft magnitudes only above threshold
{
peak[ctr] = fft_mag[ctr]; // store magnitude above threshold into peak array
freq_bin[ctr] = ctr; // location of each magnitude above threshold
frequency[ctr] = (freq_bin[ctr]*(10989/n)); // frequency calculation from magnitude location
}
}
我很抱歉没有评论代码。
peak[ctr]
包含 fft 输出的峰值幅度frequency[ctr]
包含对应的 fft 峰值幅度的频率值。
我有多个来自 fft 的峰值,输出数组如下所示;
peak[28] = [0 0 0 0 0 0 0 0 0 0 14 0 0 0 0 0 0 14 0 0 0 29 74 45 0 0 0 0]
frequency[28] = [0 0 0 0 0 0 0 0 0 0 462 0 0 0 0 0 0 714 0 0 0 924 966 1008 0 0 0 0]
因此,我需要计算:
- 平均 1 = (14x462)/14 = 462 赫兹
- 平均 2 = (14x714)/14 = 714 赫兹
- 平均 3 = (29x924 + 74x966 + 45x1008)/(29+74+45) = 938.8 赫兹
最佳答案
这是一些近似于 MCVE ( How to create a Minimal, Complete, and Verifiable Example? ) 的代码。除此之外,我通过在非零数据集之前和之间留下一组零来压缩操作/有趣的数据。问题中3项加权平均的计算似乎是错误的:
- average 3 = (29x924 + 74x966 + 45x1008)/(29+74+45) = 938.8 Hz
- 平均 3 = (26796 + 71484 + 45360)/148
- 平均 3 = 143640/148
- 平均 3 = 970.54
这与程序的计算一致。
代码:
#include <stdio.h>
int main(void)
{
enum { NUM_ENTRIES = 28 };
/* Input data */
double peak[NUM_ENTRIES] = { 0, 14, 0, 14, 0, 29, 74, 45, 0, };
double freq[NUM_ENTRIES] = { 0, 462, 0, 714, 0, 924, 966, 1008, 0, };
/* Output data */
double bin_av[NUM_ENTRIES];
int bin_lo[NUM_ENTRIES];
int bin_hi[NUM_ENTRIES];
int out = 0;
int ctr = 0;
while (ctr < NUM_ENTRIES)
{
/* Skip zeroed entries */
while (ctr < NUM_ENTRIES && (peak[ctr] == 0.0 || freq[ctr] == 0.0))
ctr++;
if (ctr < NUM_ENTRIES)
{
bin_lo[out] = ctr;
bin_hi[out] = ctr;
double w_sum = 0.0;
double f_sum = 0.0;
while (ctr < NUM_ENTRIES && (peak[ctr] != 0.0 && freq[ctr] != 0.0))
{
bin_hi[out] = ctr;
w_sum += peak[ctr] * freq[ctr];
f_sum += peak[ctr];
ctr++;
}
bin_av[out++] = w_sum / f_sum;
}
}
for (int i = 0; i < out; i++)
printf("%d .. %d: %6.1f\n", bin_lo[i], bin_hi[i], bin_av[i]);
return 0;
}
示例输出:
1 .. 1: 462.0
3 .. 3: 714.0
5 .. 7: 970.5
输出有很大的改进空间(例如,回显输入数据的相关子集并不是一个坏主意)。
有了这个框架,您可以通过从 FFT 输出中的值计算 peak
和 freq
中的值,而不是使用硬编码数组。
关于c - 查找数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720638/