matlabplotdata-fittingapproximationpolynomial-approximations

Solving Least square using MATLAB


Assume we want to determine the coefficients of a polynomial equation that is approximating the tangent function between 0 to 1, as follow:

-A is m×n vandermonde matrix. The entries are populated using m value between 0 to 11(given as input).

-The corresponding vector b is calculated using tangent function.

-x is calculated by typing x= A\b in MATLAB.

Now, using MATLAB, the computed x are subsittued in Ax. The result is plotted and it is pretty close to tangent function. But if I use polyval function of n−1 degree (in MATLAB) to calculate b, the resulting plot is significantly different from the original b. I cannot understand the reason for such a significant difference between the results of these two methods.

Here is the code:

clear all;
format long;
m = 60;
n = 11;
t = linspace(0,1,m);
A= fliplr(vander(t));
A=A(:,1:n);
b=tan(t');
x= A\b;
y=polyval(x, t);
plot(t,y,'r')
y2= A*x
hold on;
plot(t,y2,'g.');
hold on;
plot(t,tan(t),'--b');

Any insight would be appreciated. Thank you.


Solution

  • After A= fliplr(vander(t)) the A matrix is equal to

    1 t(1) t(1)^2 ...
    1 t(2) t(2)^2 ...
    ...
    1 t(m) t(m)^2 ...
    

    It is not correct because polyval accepts the coefficients in descending powers. You don't need to flip the columns of A:

    A= vander(t);
    A= A(:,end-n+1:end);