Fit data with function in MATLAB

1. Jun 29, 2013

quin

Dear users
I have some points with coordinate x and y
forexample :
x=[1 2 3 4]
and y=[2 4 6 8]
and then I want to fit these 4 pair of points with some function
for example
y=a*x+b
(here I know that the answer is a=2 and b=0)
what should I type in matlab command window?

thanks

2. Jul 1, 2013

cftool

3. Jul 1, 2013

Bill Simpson

x=[1 2 3 4];
y=[2 4 6 8];
polyfit[x, y, 1]

also

doc polyfit

4. Jul 2, 2013

quin

polyfit

and if I want to fit my points with such a finction:
y=(x-a)^n + b
what should I type in polyfit?
I mean I have some x and y values but I find the relation between x and y in a way that I have a function like y=(x-a)^n + b
and then I want to find the exact value of a,b, n?

thanks

Last edited: Jul 2, 2013
5. Jul 2, 2013

Bill Simpson

Since that isn't a polynomial you don't type anything into polyfit.

polyfit[x,y,3]
is going to find the values a,b,c,d for a*x^3+b*x^2+c*x+d to fit your data in a least squared sense.

You could go back to an old style calculus text that shows how least squared fitting is derived from taking the difference between the function and your data point, squaring that, summing that over all your data, differentiating with respect to each of your unknown coefficient variables, setting all those results equal to zero and then solving for all the coefficient variables.

Once you clearly understand how to do that then you can try to use Matlab to do some of the calculations for you.

In my experience, solving for the exponent in a least squared fit problem, n in your example, often runs into problems and it is difficult or impossible to find a solution.