Fit data with function in MATLAB

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 4K views
quin
Messages
50
Reaction score
0
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
 
Physics news on Phys.org
x=[1 2 3 4];
y=[2 4 6 8];
polyfit[x, y, 1]

also

doc polyfit
 
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:
quin said:
and if I want to fit my points with such a finction:
y=(x-a)^n + b
what should I type in polyfit?

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.