Skip to content

Instantly share code, notes, and snippets.

@johnjdavisiv
Last active August 16, 2022 18:43
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/e9ecd33061c970ddf95224f7d79b5877 to your computer and use it in GitHub Desktop.
Save johnjdavisiv/e9ecd33061c970ddf95224f7d79b5877 to your computer and use it in GitHub Desktop.
Plot frequency spectrum of timeseries data
function plotFFT(v,fs)
%plotFFT
%Plot the Fourier spectrum of a real-valued signal
%John J Davis IV
%john@johnjdavis.io
% Released under MIT license: https://opensource.org/licenses/MIT
% Input:
%
% v - (vector) signal
% fs - sample frequency in Hz
%
% Output:
% none, just plots the FFT spectrum and highlights dominant frequency
%No matrices allowed
if min(size(v)~=1)
error('Input was not a vector. Did you input a matrix instead?');
end
%Column vectors only
if size(v,1) == 1
v = v(:);
end
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 - note the change for the one middle point!
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+.05*fundHz, maxVal+0.05*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