ZelelB
ZelelB

Reputation: 2000

Polynomial regression and plotting in Matlab

Given a set of points x and a set of values y, I am trying to compute the polynomial that best fits P(x) = y in the least squared sense. The function should display the Vandermonde matrix, and the output polynomial c should be plotted as a function in form p (x) = c0*x^0 + c1*x^1 + c2*x^2 + ..... + cn-1^(n-1).

I would like to see clearely the points (xi,yi) on the same plot, where the function is plotted.

Here is what I tried so far:

function c = interpolation(x, y)
    n = length(x);
    V = ones(n);
    for j = n:-1:2
         V(:,j-1)  = x.*V(:,j);
    end
     c = V \ y;
     disp(V) 
    for i = 0:n-1
      fprintf('c%d= %.3f\n', i, c(i+1));
    end

    x = linspace(-1,2,-100);
    y = polyval(c,x);

    x0 = x;
    y0 = polyval(c,x0);

    plot(x,y,'b-')
    hold on; 
    plot(x0,y0,'ro') 
    hold off;

Upvotes: 0

Views: 1372

Answers (1)

Jonathan H
Jonathan H

Reputation: 7943

You want to take a look at polyval and linspace if you don't already know it. Also take a look at polyfit, which does the interpolation for you with a given degree. Here is your corrected code:

function [p,V] = interpolation(x0,y0,N)

    % format the inputs as columns
    x0 = x0(:);
    y0 = y0(:);

    % Build up the vandermonde matrix
    n = numel(x0);
    disp('Vandermonde matrix:');
    V = fliplr(bsxfun( @power, x0, 0:(n-1) ))

    % compute the coefficients of the fitting polynomial
    p = V \ y0;

    % plot the polynomial using N values
    x = linspace( min(x0), max(x0), N );
    y = polyval(p,x);

    plot(x,y,'b-'); hold on;
    plot(x0',y0','ro'); hold off;

end

Note: the coefficients of the polynomial, returned as p, are reversed compared to your indexing, ie they are sorted by decreasing power.

Upvotes: 1

Related Questions