Skip to content

Instantly share code, notes, and snippets.

@johnjdavisiv
Created June 30, 2020 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnjdavisiv/fdf7c275f5e923363ce60c792c49799f to your computer and use it in GitHub Desktop.
Save johnjdavisiv/fdf7c275f5e923363ce60c792c49799f to your computer and use it in GitHub Desktop.
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