Skip to content

Instantly share code, notes, and snippets.

@moorepants
Last active December 21, 2015 13:09
Show Gist options
  • Save moorepants/6310979 to your computer and use it in GitHub Desktop.
Save moorepants/6310979 to your computer and use it in GitHub Desktop.
Example of an FFT computation and plotting.
function [frequency, amplitude] = fast_fourier(time, signal, sample_rate, varargin)
% function [frequency, amplitude] = fast_fourier(time, signal, sample_rate, varargin)
%
% Parameter
% =========
% time : double, size: 1 x n
% The time vector.
% signal : double, size: 1 x n
% The signal as a function of time.
% sample_rate : double, size 1 x 1
% The sample rate of the signal.
% plot : boolean, optional
% If true a plot of the results will appear.
%
% Returns
% =======
% frequency : double, size: 1 x m
% The FFT frequencies.
% amplitude : double, size: 1 x m
% The amplitude as a function of frequency.
n = length(time); % Signal length
NFFT = 2 ^ nextpow2(n); % Next power of 2 from length of y
amplitude = fft(signal, NFFT) / n;
frequency = sample_rate / 2 * linspace(0, 1, NFFT / 2);
if length(varargin) > 0 && varargin{1}
fig = figure();
plot(frequency, 2 * abs(amplitude(1:NFFT / 2 )));
title('Single-Sided Amplitude Spectrum of the Signal');
xlabel('Frequency (Hz)');
ylabel('|Amplitude(Frequency)|');
end
% fft Fourier transform, get the right amlitude and frequency
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
% Sum of a 50 Hz sinusoid and a 120 Hz sinusoid
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);⋅
y = x + 1*randn(size(t)); % Sinusoids plus noise
figure
plot(Fs*t(1:50),y(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)')
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2);
% Plot single-sided amplitude spectrum.
figure
plot(f,2*abs(Y(1:NFFT/2)))⋅
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')⋅
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment