%% Use Spectral Entropy to Detect Sine Wave in White Noise
% Create a signal that combines white noise with a segment that consists of a sine wave. Use spectral entropy to detect the existence and position of the sine wave.
% Generate and plot the signal, which contains three segments. The middle segment contains the sine wave along with white noise. The other two segments are pure white noise.

fs = 100;
t = 0:1/fs:10;
sin_wave = 2*sin(2*pi*20*t')+randn(length(t),1);
x = [randn(1000,1);sin_wave;randn(1000,1)];
t3 = 0:1/fs:30;

plot(t3,x)
title('Sine Wave in White Noise')

% Plot the spectral entropy.

pentropy(x,fs)
title('Spectral Entropy of Sine Wave in White Noise')

% The plot clearly differentiates the segment with the sine wave from the white-noise segments. This is because the sine wave contains information. Pure white noise has the highest spectral entropy.
% The default for pentropy is to return or plot the instantaneous spectral entropy for each time point, as the previous plot displays. You can also distill the spectral entropy information into a single number that represents the entire signal by setting 'Instantaneous' to false. Use the form that returns the spectral entropy value if you want to directly use the result in other calculations. Otherwise, pentropy returns the spectral entropy in ans.

se = pentropy(x,fs,'Instantaneous',false)

% A single number characterizes the spectral entropy, and therefore the information content, of the signal. You can use this number to efficiently compare this signal with other signals.
% Copyright 2012 The MathWorks, Inc.