Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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|improve this question

2 Answers 2

up vote 3 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|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! –  Pickett Nov 18 '10 at 21:17

Use the equations here.

share|improve this answer
    
I figured there might be an easier way, considering I already got the coefficient? Also, I'm a first year undergrad and don't even know how to start implementing that. –  Pickett Nov 18 '10 at 19:37

Your Answer

 
discard

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

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