DSPRelated.com
Code

Amplitude spectrum of 1D signal

Aniket November 3, 2010 Coded in Matlab
function plot_amp_spectrum(Fs, y, varargin)
%PLOT_AMP_SPECTRUM Plot amplitude spectrum of a one dimensional signal
%   PLOT_AMP_SPECTRUM(FS, Y, COLOR, SEMILOG_SCALE, TITLE_STRING) plots the
%   amplitude spectrum of y which has sampling frency Fs. Specification
%   of color of the plot, wheather the plot is needed in semilog_scale or
%   not, and the title string for the figure are OPTIONAL.
%
%   Fs:        Sampling frequency.
%   y:         Plots the one sided amplitude spectrum of the signal with,
%   color:   color of the plot specified in string,
%   semilog_scale: [1]= Plot in log scale.
%   Example:
%   load ecg;
%   plot_amp_spectrum(hz, signal); OR
%   plot_amp_spectrum(hz, signal, 'r', 1) OR
%   plot_amp_spectrum(hz, signal, 'r', 0, 'Amplitude spectrum of ECG signal')
%--------------------------------------------------------------------------
%   Author: Aniket Vartak
%   Email: aniket.vartak@gmail.com
%   This function uses Matlab's fft() function, and builds on top of it to give
%   a handy interface to get a nicely formatted plot of the amplitude
%   spectrum.
%--------------------------------------------------------------------------

% Specify the default string incase its not provided
default_title_string = 'Single-Sided Amplitude Spectrum of y(t)';
%Deal with variable number of inputs after fs and x.
if(isempty(varargin)) % No optional information provided
    color = 'b';
    semilog_scale = 0;
    title_string = default_title_string;
end;
if(length(varargin) == 1) % Only color info provided
    color = varargin{1};
    semilog_scale = 0;
    title_string = default_title_string;
end;
if(length(varargin) == 2) % color and integer indicating semilog plot is needed is provided
    color = varargin{1};
    semilog_scale = varargin{2};
    title_string = default_title_string;
end;
if(length(varargin) == 3) % All optional info provided
    color = varargin{1};
    semilog_scale = varargin{2};
    title_string = varargin{3};
end;
%--------------------------------------------------------------------------
T = 1/Fs;                       % Sample time
L = max(size(y));            % Length of signal
NFFT = 2^nextpow2(L);  % Next power of 2 from length of y
Y = fft(y,NFFT)/L;            % Take the fourier transform
f = Fs/2*linspace(0,1,NFFT/2+1);% Space out the frequencies
set(gcf, 'Name', strcat('Amplitude Spectrum: [Fs = ',num2str(Fs),' Hz]'));
set(gcf, 'NumberTitle', 'off');
% Plot single-sided amplitude spectrum.
if (semilog_scale)
    semilogx(f,20*log10(2*abs(Y(1:NFFT/2+1))), color, 'LineWidth', 2);
else
    plot(f,20*log10(2*abs(Y(1:NFFT/2+1))), color,'LineWidth', 2);
end;
title(title_string);
xlabel('Frequency (Hz)');
ylabel('|Y(f)| dB');
grid on;