这是我在matlab中的代码:
x = [1 2 3 4];
result = fft(x);
a = real(result);
b = imag(result);
来自matlab的结果:
a = [10,-2,-2,-2]
b = [ 0, 2, 0,-2]
我在objective-c中的可运行代码:
int length = 4;
float* x = (float *)malloc(sizeof(float) * length);
x[0] = 1;
x[1] = 2;
x[2] = 3;
x[3] = 4;
// Setup the length
vDSP_Length log2n = log2f(length);
// Calculate the weights array. This is a one-off operation.
FFTSetup fftSetup = vDSP_create_fftsetup(log2n, FFT_RADIX2);
// For an FFT, numSamples must be a power of 2, i.e. is always even
int nOver2 = length/2;
// Define complex buffer
COMPLEX_SPLIT A;
A.realp = (float *) malloc(nOver2*sizeof(float));
A.imagp = (float *) malloc(nOver2*sizeof(float));
// Generate a split complex vector from the sample data
vDSP_ctoz((COMPLEX*)x, 2, &A, 1, nOver2);
// Perform a forward FFT using fftSetup and A
vDSP_fft_zrip(fftSetup, &A, 1, log2n, FFT_FORWARD);
//Take the fft and scale appropriately
Float32 mFFTNormFactor = 0.5;
vDSP_vsmul(A.realp, 1, &mFFTNormFactor, A.realp, 1, nOver2);
vDSP_vsmul(A.imagp, 1, &mFFTNormFactor, A.imagp, 1, nOver2);
printf("After FFT: \n");
printf("%.2f | %.2f \n",A.realp[0], 0.0);
for (int i = 1; i< nOver2; i++) {
printf("%.2f | %.2f \n",A.realp[i], A.imagp[i]);
}
printf("%.2f | %.2f \n",A.imagp[0], 0.0);
目标c的输出:
After FFT:
10.0 | 0.0
-2.0 | 2.0
结果非常接近。我想知道其余的在哪里?我知道错过了什么,但不知道它是什么。
更新:我找到了另一个答案here。我更新了输出
After FFT:
10.0 | 0.0
-2.0 | 2.0
-2.0 | 0.0
但即便如此,仍有1个元素缺少-2.0 | -2.0
答案 0 :(得分:2)
执行FFT可提供右手光谱和左手光谱。 如果您有N个样本,您将返回的频率为:
( -f(N/2), -f(N/2-1), ... -f(1), f(0), f(1), f(2), ..., f(N/2-1) )
如果A(f(i))是频率分量f(i)的复振幅A,则以下关系为真:
Real{A(f(i)} = Real{A(-f(i))} and Imag{A(f(i)} = -Imag{A(-f(i))}
这意味着,右手光谱和左手光谱的信息是相同的。但是,虚部的符号是不同的。
Matlab以不同的顺序返回频率。 Matlab的顺序是:
( f(0), f(1), f(2), ..., f(N/2-1) -f(N/2), -f(N/2-1), ... -f(1), )
要获得高阶,请使用Matlab函数fftshift()。
对于4个样本,你有Matlab:
a = [10,-2,-2,-2]
b = [ 0, 2, 0,-2]
这意味着:
A(f(0)) = 10 (DC value)
A(f(1)) = -2 + 2i (first frequency component of the right hand spectrum)
A(-f(2) = -2 ( second frequency component of the left hand spectrum)
A(-f(1) = -2 - 2i ( first frequency component of the left hand spectrum)
我不明白你的目标-C代码。 但是,在我看来,该程序仅返回右手谱。 所以一切都很完美。