Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|cite|improve this question
    
Use the equations here. – Yuval Filmus Nov 18 '10 at 19:32
up vote 2 down vote accepted

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$.

share|cite|improve this answer
    
You are right. I said constant, instead of coefficient, and in my mind there was no doubt that polyfit would not give me the constant. So I can see that I confused you. Polyfit DOES find the constant, even in my version of Matlab. It now works! – user3680 Nov 18 '10 at 21:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.