%% Noisy Signal
% The Fourier transform can compute 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.

rng('default')
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*randn(size(t));                  % Gaussian noise;

%
% The Fourier transform of the signal identifies its frequency components. In MATLAB®, the fft 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 fftshift 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')

% Copyright 2012 The MathWorks, Inc.