% Lecture 12, question 2 % to get a plot for part a clear; close all; m = 10; n = 5; dx = 2/(n-1); x = -1:dx:1; dy = 2/(m-1); y = -1:dy:1; % let f(x) = abs(x); f = abs(x); f = f'; % create vandermonde matrix V = vander(x); % put it into a least squares formulation V = fliplr(V); % get coefficients of polynomial, Ac = f c = V\f; % the polynomial interpolant has the form % p(x) = c(1) + c(2)x + c(3)x^2 + ... % form polynomial interpolant p = 0; for i = 1:n p = p + c(i)*y.^(i-1); end % to generate the data points directly via multiplication % by an m x n matrix A. % Y = fliplr(vander(y)) % Y = Y(:,1:n); % A = Y * inv(V); % p = A*f; subplot(1,2,1); plot(x,f,'r-',x,f,'ro',y,p,'b-'); legend('actual function','data points','interpolant'); title('n = 10'); xlabel('x'); ylabel('f(x)'); m = 100; n = 20; dx = 2/(n-1); x = -1:dx:1; dy = 2/(m-1); y = -1:dy:1; % let f(x) = abs(x); f = abs(x); f = f'; %f = ones(n,1); %f(2) = 1+ 1e-8; % create vandermonde matrix V = vander(x); % put it into a least squares formulation V = fliplr(V); % get coefficients of polynomial, Ac = f c = V\f; % the polynomial interpolant has the form % p(x) = c(1) + c(2)x + c(3)x^2 + ... % form polynomial interpolant p = 0; for i = 1:n p = p + c(i)*y.^(i-1); end subplot(1,2,2); plot(x,f,'r-',x,f,'ro',y,p,'b-'); legend('actual function','data points','interpolant'); title('n = 20'); xlabel('x'); ylabel('f(x)');