Calculate the magnitude and phase of input frame using FFT IFFT C语言
时间: 2024-03-20 10:40:11 浏览: 82
FFT及IFFT的C语言实现
Sure, here is an example code to calculate the magnitude and phase of an input frame using FFT and IFFT in C language:
```c
#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <fftw3.h>
#define N 256 // Input frame size
int main()
{
double input[N]; // Input frame
double output[N]; // Output frame
double magnitude[N/2+1]; // Magnitude spectrum
double phase[N/2+1]; // Phase spectrum
// Initialize input frame (for example, with a sine wave)
for (int i = 0; i < N; i++) {
input[i] = sin(2*M_PI*i/N);
}
// Perform FFT
fftw_complex fft_output[N/2+1];
fftw_plan fft_plan = fftw_plan_dft_r2c_1d(N, input, fft_output, FFTW_ESTIMATE);
fftw_execute(fft_plan);
fftw_destroy_plan(fft_plan);
// Calculate magnitude and phase
for (int i = 0; i < N/2+1; i++) {
magnitude[i] = cabs(fft_output[i]);
phase[i] = carg(fft_output[i]);
}
// Perform IFFT
fftw_plan ifft_plan = fftw_plan_dft_c2r_1d(N, fft_output, output, FFTW_ESTIMATE);
fftw_execute(ifft_plan);
fftw_destroy_plan(ifft_plan);
// Normalize output frame
for (int i = 0; i < N; i++) {
output[i] /= N;
}
// Print results
for (int i = 0; i < N/2+1; i++) {
printf("Bin %d: Magnitude = %f, Phase = %f\n", i, magnitude[i], phase[i]);
}
return 0;
}
```
In this code, we first initialize an input frame of size N (in this case, a sine wave). We then perform FFT using the `fftw_plan_dft_r2c_1d` function from the FFTW library. This function takes the input frame, the output buffer (in this case, a complex array `fft_output`), and a flag indicating the FFT algorithm to use (`FFTW_ESTIMATE` in this case, which is a good default choice). We then calculate the magnitude and phase of each frequency bin using the `cabs` and `carg` functions from the C standard library, respectively. Finally, we perform IFFT using the `fftw_plan_dft_c2r_1d` function, and normalize the output frame by dividing by N. The results are printed to the console.
Note that this code is just an example, and may need to be modified depending on the specific requirements of your application.
阅读全文