www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/BasicSpectralAnalysisExample.m

    %% Noisy Signal
% This example computes the frequency components of a signal that is corrupted
% by random noise.

%%
% Create a signal with component frequencies at 15 Hz and 40 Hz, and inject random
% Gaussian noise.
fs = 100;                                % sample frequency (Hz)
t = 0:1/fs:10-1/fs;                      % 10 second span time vector
x = (1.3)*sin(2*pi*15*t) ...             % 15 Hz component
  + (1.7)*sin(2*pi*40*(t-2)) ...         % 40 Hz component
  + 2.5*gallery('normaldata',size(t),4); % Gaussian noise;

%% 
% The Fourier transform of the signal identifies its frequency components.
% In MATLAB(R), the <docid:matlab_ref.f83-998360> function computes the
% Fourier transform using a fast Fourier transform algorithm. Use |fft| to
% compute the discrete Fourier transform of the signal.
y = fft(x);             

%%
% Plot the power spectrum as a function of frequency. While noise disguises
% a signal's frequency components in time-based space, the Fourier
% transform reveals them as spikes in power.
n = length(x);          % number of samples
f = (0:n-1)*(fs/n);     % frequency range
power = abs(y).^2/n;    % power of the DFT

plot(f,power)
xlabel('Frequency')
ylabel('Power')

%%
% In many applications, it is more convenient to view the power spectrum
% centered at 0 frequency because it better represents the signal's
% periodicity.  Use the <docid:matlab_ref.f83-998509> function to perform a
% circular shift on |y|, and plot the 0-centered power.
y0 = fftshift(y);         % shift y values
f0 = (-n/2:n/2-1)*(fs/n); % 0-centered frequency range
power0 = abs(y0).^2/n;    % 0-centered power

plot(f0,power0)
xlabel('Frequency')
ylabel('Power')