clear; clc; close all;

rng(3); % fix the random seed
N = 10;
x = linspace(0, 1, N); x = x(:);
y = cos(rand(size(x)) * pi / 2) + x .^ 2;
figure; hold on; grid on; plot(x, y, 'o');

% A = [x .^ 3, x .^ 2, x, ones(N, 1)];
% coeff = A \ y
% xq = linspace(0, 1, 30); xq = xq(:);
% yq = [xq .^ 3, xq .^ 2, xq, ones(30, 1)] * coeff;
% plot(xq, yq, 'r--');

% degree = 12
% M = @(x, degree) repmat(x, 1, degree + 1);
% A = @(mat) bsxfun(@(x, i) x .^ i, mat, size(mat, 2) - 1 : -1 : 0);
% pp = A(M(x, degree)) \ y % show the coefficients
% 
% yq = A(M(xq, degree)) * pp;
% plot(xq, yq, '--');
% yq = cos(xq * pi / 2) + xq .^ 2;
% plot(xq, yq, ':');

xq = linspace(min(x) - 0.025, max(x) + 0.025, 100); xq = xq(:);
for degree = 1 : 10
    
    p = polyfit(x, y, degree);
    yq = polyval(p, xq);
    plot(xq, yq, '--');
    
end


