c语言实现傅里叶变换,并翻译成MATLAB
时间: 2023-05-24 18:05:59 浏览: 104
C语言实现傅里叶变换:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
typedef struct {
double re;
double im;
} complex;
void fft(complex *x, int N) {
if (N <= 1) return;
complex *even = (complex *)malloc(N/2 * sizeof(complex));
complex *odd = (complex *)malloc(N/2 * sizeof(complex));
for (int i = 0; i < N/2; i++) {
even[i] = x[2*i];
odd[i] = x[2*i+1];
}
fft(even, N/2);
fft(odd, N/2);
for (int k = 0; k < N/2; k++) {
complex t = {cos(2*PI*k/N), -sin(2*PI*k/N)};
t.re *= odd[k].re;
t.im *= odd[k].im;
odd[k].re = even[k].re - t.re;
odd[k].im = even[k].im - t.im;
even[k].re += t.re;
even[k].im += t.im;
x[2*k] = even[k];
x[2*k+1] = odd[k];
}
free(even);
free(odd);
}
int main() {
int N = 8; // 8个采样点
double x[] = {1, 1, 1, 1, 0, 0, 0, 0}; // 4个正弦波的采样值
complex *X = (complex *)malloc(N * sizeof(complex));
for (int i = 0; i < N; i++) {
X[i].re = x[i];
X[i].im = 0;
}
fft(X, N);
for (int i = 0; i < N; i++) {
printf("X[%d] = (%f, %f)\n", i, X[i].re, X[i].im);
}
free(X);
return 0;
}
```
MATLAB实现傅里叶变换:
```matlab
N = 8; % 8个采样点
x = [1 1 1 1 0 0 0 0]; % 4个正弦波的采样值
X = fft(x, N);
for i = 1:N
fprintf('X[%d] = (%f, %f)\n', i-1, real(X(i)), imag(X(i)));
end
```
阅读全文