write the fft function without using the built in fft function and then plot the results in matlab

To write the FFT function without using the built-in function, we can use the Cooley-Tukey algorithm. Here's the code:

main.m
function Y = myFFT(X)
% Computes the FFT of the input signal X using the Cooley-Tukey algorithm

N = length(X);
halfN = N/2;
expo = -2i*pi/N;
W = exp(expo*(0:halfN-1));

if N == 1
    Y = X;
elseif mod(N,2) == 0
    X_even = myFFT(X(1:2:end));
    X_odd = myFFT(X(2:2:end));
    Y = [X_even+W.*X_odd X_even-W.*X_odd];
else
    X_even = myFFT(X(1:2:end-1));
    X_odd = myFFT(X(2:2:end));
    Y = [X_even+W.*X_odd X_even-W.*X_odd X_odd(end)];
end
446 chars
20 lines

The input to this function is a time-domain signal X, and the output is the frequency-domain signal Y. To plot the results, we can use the following code:

main.m
Fs = 1000;              % Sampling frequency
T = 1/Fs;               % Sampling period
L = length(Y);          % Length of signal
t = (0:L-1)*T;           % Time vector
f = Fs*(0:(L/2))/L;     % Frequency vector

figure
subplot(2,1,1)
plot(t,X)
axis([0 max(t) min(X) max(X)])
title('Time Domain Signal')
xlabel('Time (s)')
ylabel('Amplitude')

subplot(2,1,2)
plot(f,2*abs(Y(1:L/2+1)))
axis([0 max(f) 0 max(abs(Y))*2])
title('Frequency Domain Signal')
xlabel('Frequency (Hz)')
ylabel('Magnitude')
496 chars
21 lines

This code first sets up the time-domain signal X and the frequency-domain signal Y, and then creates time and frequency vectors based on the sampling frequency Fs and the length of the signal L. The plot function is then used to plot both the time-domain signal and the frequency-domain signal on separate subplots.

You can then call myFFT function with your own signal X and plot the result using this code.

gistlibby LogSnag