You are on page 1of 1

% 2

rng(42);
% (a)
N = 6;
x = linspace(0, 1, N)';
t = 2*x - 3 + sqrt(3)*randn(N, 1); % Adding random distributed noise as N(0,3)
lambda_values = [0, 1e-6, 0.01, 0.1];
X = [ones(N, 1), x, x.^2, x.^3, x.^4, x.^5];

hold on
scatter(x, t, 'LineWidth', 2, DisplayName='Data points');
% Generate x values for the plotting the polynomial
x_values = linspace(-1, 2, 100);

% (b), (c)
% Fit fifth order model for different values of lambda
for lambda = lambda_values
w_hat = (X'*X+N*lambda*eye(N))\(X'*t);
w_hat = flip(w_hat);
y_values = polyval(w_hat, x_values);
% Plot the polynomial
plot(x_values, y_values, 'LineWidth', 2, 'DisplayName', sprintf('lambda = %f',
lambda));
end

% Add axis titles, limits and legend


xlabel('x');
ylabel('t');
legend('Location', 'SouthWest', 'FontSize', 8);
grid on;
xlim([-0.9 1.7])
ylim([-10 4])
hold off

You might also like