%% Adjust Smoothing Parameters and Weights
% Adjust the smoothing parameter, error measure weights, and roughness measure weights.
% Create a sine curve with noise.

x = linspace(0,2*pi,21); y = sin(x)+(rand(1,21)-.5)*.3;

% Fit a smoothing spline to the data. Specify the smoothing parameter p = 0.4 and error measure weights w that vary across the data.

pp = csaps(x,y,0.4,[],[ones(1,10),repmat(5,1,10), 0]);

% The function returns a smooth fit to the noisy data that is much closer to the data in the right half because of the much larger error measure weight there. Note that the error weighting of zero for the last data point excludes this point from the fit.
% Now fit a smoothing spline using the same data, smoothing parameter and error measure weights, but with adjusted roughness measure weights.

pp1 = csaps(x,y, [.4,ones(1,10),repmat(.2,1,10)], [], ...
                    [ones(1,10), repmat(5,1,10), 0]);

% The roughness measure weight is only 0.2 in the right half of the interval. Correspondingly, the fit is rougher but closer on the right side of the data (except for the last data point, which is ignored).
% Plot both fits for comparison.

figure
hold on
fnplt(pp, 'b'); 
fnplt(pp1,'r--')
plot(x,y,'ok')
hold off
ylim([-1.5 1.5])
title(['Cubic smoothing spline, with right half treated ',...
          'differently'])
legend('Larger error weight', 'Larger error and smaller roughness weight')

% Copyright 2018 The MathWorks, Inc.