Search code examples
matlabmatlab-figurepolynomialspolynomial-approximations

Fitting a n ordered polynomial


I was trying to plot a regression curve:

coef_fit = polyfit(norm_dist,norm_time,7); 
y_fit = polyval(coef_fit,xlim); 
plot(xlim,y_fit,'r');

But it is always plotting a line respective of the order I pass.


Solution

  • The problem is that the x values you are using are the output ot xlim, which is a length-2 vector. You need to define an x vector with more values:

    norm_dist = sort(5*randn(1,50) + (1:50)); %// example x values
    norm_time = 5*randn(1,50) + (1:50).^2; %// example y values
    x = linspace(min(norm_dist), max(norm_dist), 200); %// define x values for plot
    coef_fit = polyfit(norm_dist,norm_time,7); 
    y_fit = polyval(coef_fit,x); 
    plot(x,y_fit,'r');
    hold on
    plot(norm_dist, norm_time, 'b.') %// plot original points for comparison
    

    enter image description here