%% Steady-State and Transient Savitzky-Golay Filters
% Generate a random signal and smooth it using sgolayfilt. Specify a polynomial order of 3 and a frame length of 11. Plot the original and smoothed signals.

order = 3;
framelen = 11;

lx = 34;
x = randn(lx,1);

sgf = sgolayfilt(x,order,framelen);

plot(x,':')
hold on
plot(sgf,'.-')
legend('signal','sgolay')

%
% The sgolayfilt function performs most of the filtering by convolving the signal with the center row of B, the output of sgolay. The result is the steady-state portion of the filtered signal. Generate and plot this portion.

m = (framelen-1)/2;

B = sgolay(order,framelen);

steady = conv(x,B(m+1,:),'same');

plot(steady)
legend('signal','sgolay','steady')

%
% Samples close to the signal edges cannot be placed at the center of a symmetric window and have to be treated differently.
% To determine the startup transient, matrix multiply the first (framelen-1)/2 rows of B by the first framelen samples of the signal.

ybeg = B(1:m,:)*x(1:framelen);

%
% To determine the terminal transient, matrix multiply the final (framelen-1)/2 rows of B by the final framelen samples of the signal.

yend = B(framelen-m+1:framelen,:)*x(lx-framelen+1:lx);

%
% Concatenate the transients and the steady-state portion to generate the complete signal.

cmplt = steady;
cmplt(1:m) = ybeg;
cmplt(lx-m+1:lx) = yend;

plot(cmplt)
legend('signal','sgolay','steady','complete')
hold off

% Adding weights to the minimization breaks the symmetry of B and requires extra steps for a proper solution.
% Copyright 2012 The MathWorks, Inc.