Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Plot FFT of a signal
function plotFFT(v,fs)
%plotFFT Quick function to plot the frequency content of a signal
% Input:
%
% v - (vector) signal
% fs - sample frequency in Hz
%
% Output:
% none, just plots the FFT spectrum and highlights dominant frequency
%John J Davis IV
n = length(v);
detrend_v = detrend(v, 'constant');
myFFT = fft(detrend_v);
myFFT = myFFT(1:floor(n/2)); %FFT is symmetric, keep first half
freqHz = (0:(floor(n/2)-1))*fs/n; %Frequency axis label
myFFTmag = abs(myFFT);
%Fundamental frequency, i.e. average step frequency during the run
[maxVal, fundIndex] = max(myFFTmag);
fundHz = freqHz(fundIndex);
f = figure('Position', [200 200 1000 600]);
hold on;
plot(freqHz, myFFTmag);
plot(fundHz, maxVal, 'v', 'MarkerFaceColor', 'k', 'MarkerEdgeColor', 'k',...
'MarkerSize',8);
text(fundhz, maxVal, sprintf('%.2f Hz', fundHz));
hold off;
xlabel('Frequency (Hz)');
ylabel('Magnitude');
f.Children.FontSize = 16;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment