[Math] Find equation of curve fit programmatically in Matlab

math-softwareMATLABregressionstatistics

In MATLAB, when you plot something, there's a tool available which is called "curve fitting". And if you have a set of data points and a linear correlation, this tool will easily come up with an equation on the form y = ax + c.

I want to do exactly that, but I need to do it programmatically. I know that I can use polyfit to find the coefficient, and polyval to evaluate as many data points as I want, but what I can't figure out is how to find the constant c. This is very important, since I need to be able to plot the line as well next to my data points.

Thank you.

Best Answer

I'm going to give two answers.


Answer 1: If you already know $a$, then $c = \bar{y} - a\bar{x}$, where $\bar{x}$ and $\bar{y}$ are the means of the $x$ and $y$ values, respectively. (This is actually in that pile of formulas in the link provided by Yuval Filmus.)


Answer 2: At least in my version of Matlab, polyfit gives both $a$ and $c$. For example, if you generate a set of data via (I'm modifying the example given in the Matlab help)

x = (0: 0.1: 2.5)';
y = erf(x); 

and then call polyfit with $n=1$ (for a linear curve fit, or linear regression)

p = polyfit(x,y,1)

The output is

0.3554    0.3191

which means your linear equation is $y = 0.3554x + 0.3191$.