Search code examples
matlabloopsmatrixpolynomials

Storing in a matrix - n polynomials of degree (n-1), one row for each x


Im trying to write a matlab-program were the user inputs n number of points, then n coordinate pairs are chosen graphically (with ginput). I then want to create an interpolation-polynomial of degree (n-1) through the chosen points and solve for the coefficients of that interpolation-polynomial.

So I'm thinking that I want to store all the points in a matrix like this:

1 x1 x1^2 x1^3 ... x1^(n-1)
.
.
1 xn xn^2 xn^3 ... xn^(n-1)

.. and then solve for the coefficients with the backslash-operator. My code so far is like this:

n = input('How many points?');

[x,y] = ginput(n);

A = zeros(n);

for i = 1:n
    A(1,i) = [x(1)^(i-1)];
end

And my problem is that I'm not able to create a successful loop that gives me new rows according to the pattern of how I want to store the points in polynomial form (like illustrated above). How do I write to store n number of rows with each row using the one x at the time for each row and rasing it to (n-1) degrees for every row?


Solution

  • You are almost there, you are able to create a single line of that matrix, you are just lacking iteration over the amount of points:

    for j=1:length(x)
      for i = 1:n
          A(j,i) = [x(j)^(i-1)];
      end
    end