# How to validate this Matlab code?

I am new to Matlab, help please. In the book I saw this picture for the following polynomial: $$g(t)=x_1+x_2t+x_3t^2+ \ldots +x_{10}t^9$$ for some $t$ and $g(t)$.

The following code is given:

t=transpose(linspace(-1,1,50))
y=1./(1+25*t.^2)
n=10
A=fliplr(vander(t))
A=A(:,1:n)
x=A\y
u=linspace(-1,1,1000)
g=x(n)*ones(1,1000)
for i=(n-1):-1:1
g=g.*u+x(i)
end
plot(u,g,'-',t,y,'o')


I am trying this code in Matlab but not getting the same picture. I think I need to input some code at first, before the above written code, that somehow tells to Matlab the code is for polynomial of degree 9. I do not see how this code tells about polynomial degree to Matlab.

What do I need to do to get the same picture?

-

I just copied and pasted that code into a new .m file and ran it, without adding any extra code at all, and I got the correct plot.

Here's my code (exactly the same as the code given in your question):

-
Did you write anything to represent this polynomial: $g(t)=x_1+x_2t+x_3t^2+ \ldots +x_{10}t^9$. If no, then how matlab understood that this polynomial is degree 9, if i were to do the same for degree 2, which code should i changed? Thanks –  ASROMA Nov 5 '12 at 1:25
I literally wrote nothing, I just copied your code with ctrl+c and pasted it with ctrl+v, then ran the code. I'll edit my answer to include my code. What happens for you when you run the code? –  littleO Nov 5 '12 at 1:36
The line $A = A(:1:n)$ with $n = 10$ is doing something specific to the fact that you have a polynomial of degree $9$. If you want to use a degree 2 polynomial instead, just change $n$ to $3$. –  littleO Nov 5 '12 at 1:45
Ok i got that to, i guess had some extra code there, had to delete everything :) –  ASROMA Nov 5 '12 at 1:45

MATLAB is a vector-based language (like the open-source Octave).In this case, variable x is a vector of length 10, which represents 10 coefficients of a polynomial. In your code, polynomial evaluation is given by Horner's method, however in MATLAB or Octave it can be much more simple by using polyval function:

plot(u, polyval(x(end:-1:1),u))

MATLAB (or Octave) interprets x as a polynomial of degree 9 (i.e., 10 coefficients). Here is your code on Octave.

-