how to plot the fft of a vector in matlab

To plot the FFT of a vector in Matlab, you can follow these steps:

  1. Define a vector, for example x = sin(2*pi*1000*[0:1/44100:1]); where 1/44100 is the sampling frequency, and 2*pi*1000 is the frequency of the sine wave.
  2. Take the FFT using y = fft(x);. Note that this computes the complex Fourier coefficients of the input vector.
  3. Compute the single-sided spectrum by only keeping the first half of the FFT output (due to the symmetry of the Fourier transform): ysingle = y(1:length(x)/2+1);.
  4. Compute the corresponding frequency vector: freq = 0:1/length(x):44100/2;.
  5. Plot the result using plot(freq, abs(ysingle));. Note that taking the absolute value of the Fourier coefficients gives the amplitude, and not the phase information.

Here is the final code:

main.m
% Define input vector
x = sin(2*pi*1000*[0:1/44100:1]);

% Compute FFT
y = fft(x);

% Compute single-sided spectrum
ysingle = y(1:length(x)/2+1);

% Create frequency vector
freq = 0:1/length(x):44100/2;

% Plot the result
plot(freq, abs(ysingle));
248 chars
15 lines

gistlibby LogSnag