discrete fourier transform in for loop in matlab

For discrete fourier transform using for loop in MATLAB, you can use the following code. In this code, we define a signal x and calculate its fourier transform using a for loop.

main.m
% Define the signal
N = 1024; % Number of samples
Fs = 1000; % Sampling frequency
t = (0:N-1)/Fs; % Time vector
f0 = 50; % Signal frequency
x = cos(2*pi*f0*t) + 2*cos(2*pi*2*f0*t) + 0.5*sin(2*pi*4*f0*t); % Signal

% Calculate Fourier transform using for loop
X = zeros(1, N); % Initialize Fourier transform
for k = 1:N
    for n = 1:N
        X(k) = X(k) + x(n)*exp(-1j*2*pi*(k-1)*(n-1)/N);
    end
end

% Plot the signal and its Fourier transform
subplot(2,1,1)
plot(t, x)
xlabel('Time (s)')
ylabel('Amplitude')
title('Signal')
subplot(2,1,2)
f = (0:N-1)*(Fs/N); % Frequency vector
plot(f, abs(X))
xlabel('Frequency (Hz)')
ylabel('Magnitude')
title('Fourier Transform')
671 chars
28 lines

In the above code, we initialize the Fourier transform X to be zero and then using two nested for loops, we calculate the Fourier transform as per the formula. Finally, we plot the signal and its Fourier transform.

gistlibby LogSnag