%% Locate Signal in Data
% Generate a data set consisting of a 5 Hz Gaussian pulse with 50% bandwidth, sampled for half a second at a rate of 1 kHz.

fs = 1e3;

t = 0:1/fs:0.5;
data = gauspuls(t,5,0.5);

%
% Create a signal consisting of one-and-a-half cycles of a 10 Hz sinusoid. Plot the data set and the signal.

ts = 0:1/fs:0.15;
signal = cos(2*pi*10*ts);

subplot(2,1,1)
plot(t,data)
title('Data')
subplot(2,1,2)
plot(ts,signal)
title('Signal')

%
% Find the segment of the data that has the smallest squared Euclidean distance to the signal. Plot the data and highlight the segment.

figure
findsignal(data,signal)

%
% Add two clearly outlying sections to the data set. Find the segment that is closest to the signal in the sense of having the smallest absolute distance.

dt = data;
dt(t>0.31&t<0.32) = 2.1;
dt(t>0.32&t<0.33) = -2.1;

findsignal(dt,signal,'Metric','absolute')

%
% Let the x-axes stretch if the stretching results in a smaller absolute distance between the closest data segment and the signal.

findsignal(dt,signal,'TimeAlignment','dtw','Metric','absolute')

%
% Add two more outlying sections to the data set.

dt(t>0.1&t<0.11) = 2.1;
dt(t>0.11&t<0.12) = -2.1;

findsignal(dt,signal,'TimeAlignment','dtw','Metric','absolute')

%
% Find the two data segments closest to the signal.

findsignal(dt,signal,'TimeAlignment','dtw','Metric','absolute', ...
    'MaxNumSegments',2)

%
% Go back to finding one segment. Choose 'edr' as the x-axis stretching criterion. Select an edit distance tolerance of 3. The edit distance between nonmatching samples is independent of the actual separation, making 'edr' robust to outliers.

findsignal(dt,signal,'TimeAlignment','edr','EDRTolerance',3, ...
    'Metric','absolute')

%
% Repeat the calculation, but now normalize the data and the signal.
% Define a moving window with 10 samples to either side of each data and signal point.
% Subtract the mean of the data in the window and divide by the local standard deviation.
% Find the normalized data segment that has the smallest absolute distance to the normalized signal. Display the unnormalized and normalized versions of the data and the signal.

findsignal(dt,signal,'TimeAlignment','edr','EDRTolerance',3, ...
    'Normalization','zscore','NormalizationLength',21, ...
    'Metric','absolute','Annotate','all')

% Copyright 2012 The MathWorks, Inc.