function sheet10

% generate some data
N = 50;
X = 2 * pi * rand(N, 1);
Y = fct1(X) + randn(N, 1);

% plot the data
hold off;
plot(X, Y, '.');
grid;

% plot the linear fit without centering
hold on;
W = lsr(X, Y)
plot_fit(X, Y, W, 0, 'r-');

% ... and with centering
[W, B] = lsr_with_centering(X, Y);
plot_fit(X, Y, W, B, 'b-');

% plot a polynomial fit for 4 different regularization constants
for lambda = [1, 10, 100, 1000]
W = lsr_poly(4, lambda, X, Y);
plot_poly_fit(4, W, X, Y, 'k-');
end

hold off;

legend('data', 'without centering', 'with centering', 'poly')

function Y = fct1(X)
Y = 0.2 * (X - pi - 1) .* (X - pi - 2.5) .* (X - pi + 1) .* X - 3;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fill in your solutions below

% 1. Center the data
function X = center(X)
% ...

% 2. Compute the least-squares fit from X and Y
function W = lsr(X, Y)
% ...

% 3. Compute the centered version. Compute W and B accordingly.
function [W, B] = lsr_with_centering(X, Y)
XM = mean(X);
YM = mean(Y);
X = center(X);
Y = center(Y);

% ...

function plot_fit(X, Y, W, B, style)
X = sort(X);
Yh = W'*X + B;
plot(X, Yh, style);

% 4. Compute the least-squares fit using the function
% poly_design_matrix.
function W = lsr_poly(K, lambda, X, Y)
% ...

% 5. Compute the design matrix for polynomials from degree 0 to K
function PSI = poly_design_matrix(K, X)
% ...

% 6. Compute the prediction using for polynomials from degree 0 to K
function W = plot_poly_fit(K, W, X, Y, style)
X = sort(X);
% ...
plot(X, Yh, style);