将 fft 代码从 Matlab 转换为 C#

Converting fft code from Matlab to C#

我正在使用 C# 的 LomontFFT 算法。 Matlab中的代码如下:

idx = 3000 : 5048;
figure      
hold on
plot(abs(fft(a_eeg1_raw(idx))), 'y')
%Title,xlabel,ylabel etc

所以我尽力在 C# 中做完全相同的事情:

int idx_start = 3000 + 1;
int idx_end = 5048;
LomontFFT my_fft = new LomontFFT();
double[] temp = new double[idx_end - idx_start + 1];
for (int i = idx_start, j = 0; i < idx_end + 1; i++, j++)
   temp[j] = a_eeg1_raw[i];
my_fft.RealFFT(temp, true); // With (A,B) (1,-1) - signal processing
for (int i = 3, j = 1; i < temp.Count() - 1; i = i + 2, j++) // as long as first to entries have only real parts I'm starting from 3rd entry (imaginary part)
   series_a_eeg1_fft.Points.Add(new DataPoint(Convert.ToDouble(j), Math.Abs(temp[i])));
for (int i = temp.Count() - 1, j = seria_a_eeg1_raw.Points.Count() - 1; i > 2; i = i - 2, j++)
   series_a_eeg1_fft.Points.Add(new DataPoint(Convert.ToDouble(j), Math.Abs(temp[i])));
model_tab1.PlotModel.Series.Add(series_a_eeg1_fft);

我从这段代码中得到的值与在 Matlab 中得到的值有很大不同。情节的形状并没有太大的不同,反正它不一样。我很确定我忘记了一些重要的事情,但在盯着这段代码看了 3 小时后,我找不到问题所在。有人可以帮助我吗?

abs(fft(x))abs(real(fft(x))) 不同。您没有正确组合实部和虚部。

假设this is the documentation

Compute the forward or inverse Fourier Transform of data, with
data containing real valued data only. The output is complex
valued after the first two entries, stored in alternating real
and imaginary parts
. The first two returned entries are the real
parts of the first and last value from the conjugate symmetric
output, which are necessarily real