Improve Example 6.5.1 to work with polynomials of any degree \(d\text{,}\) and add a computation of \(R^2\) to it.
Solution.
x = (0:14)';
y = [9 8 5 5 3 1 2 5 4 7 8 8 7 7 8]'; % data
d = 2; % degree of polynomial
X = x.^(0:d); % matrix of linear system for parameters
beta = X\y; % optimal parameters
f = @(x) (x.^(0:d))*beta; % best-fitting function f
t = linspace(min(x), max(x), 1000)';
plot(t, f(t), 'b', x, y, 'r*')
total = norm(y - mean(y))^2;
residual = norm(y - f(x))^2;
fprintf('R^2 for degree %d is %g\n', d, 1 - residual/total);
