I have a data set of x- and y-values, that I want make a linear fit on. Using polyfit(x,y,1) I get the coefficients a and b for a linear fit y=ax+b for this data, but I would also like to find the uncertainty or standard deviation for these coefficients. Does anyone know an easy way of doing this?

My Google-fu only gave me this result, and seeing as the last answer in that thread is a correction to first answer, I don't know if I should trust any of the answers. The answer from that thread is:

ste = sqrt(diag(inv(s.R)*inv(s.R')).*s.normr.^2./s.df);
  • $\begingroup$ I am not seeing how to retrieve something like a_uncert or b_uncert from freude's answer. Can anyone clarify that? $\endgroup$
    – Damian
    Aug 5, 2014 at 9:10

2 Answers 2


Everything can be done with polyfit function only. Read about its optional output parameters in http://www.mathworks.nl/help/matlab/ref/polyfit.html

For instance:

[p,S,mu] = polyfit(x,y,n)

where mu is the two-element vector [μ1,μ2], where μ1=mean(x), μ2=std(x)

To compute error, you have to use another function taking output of polyfit:

[y,delta] = polyval(p,x,S,mu)

This function computes polynomial function from coefficients and estimates the error.

  • 1
    $\begingroup$ This is probably the latest reply ever, but thanks for the answer! Marked it as correct now. $\endgroup$
    – Filip S.
    Apr 2, 2014 at 11:52

If you have the curve fitting toolbox installed, you can use fit to determine the uncertainty of the slope a and the y-intersect b of a linear fit. Note: x and y have to be column vectors for this example to work.

cf = fit(x,y,'poly1'); 

The option 'poly1' tells the fit function to perform a linear fit. The output is a "fit object". You can access the fit results with the methods coeffvaluesand confint. Assuming that the confidence intervals are symmetrically spaced around the fitted values (which in my experience is true in all reasonable cases), you can use the following code:

cf_coeff = coeffvalues(cf);
cf_confint = confint(cf);
a = cf_coeff(1);
b = cf_coeff(2);
a_uncert = (cf_confint(2,1) - cf_confint(1,1))/2;
b_uncert = (cf_confint(2,2) - cf_confint(1,2))/2;

One note of caution: The errors of a and b will generally be correlated, which makes them unnecessarily big. You can reduce this correlation by subtracting the mean x-value of your data before fitting. My Statistics skills aren't good enough to provide a solid explanation on the reasons for that - hopefully one of the more seasoned statistics experts can edit my answer (or provide their own and delete mine) to give details on this side-note.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.