MATLAB Fit data with function in MATLAB

AI Thread Summary
To fit data points in MATLAB using a linear function, the command "polyfit(x, y, 1)" can be used, where x and y are your data arrays. For fitting a non-polynomial function like y=(x-a)^n + b, polyfit is not suitable, as it is designed for polynomial fitting. Instead, understanding least squares fitting through calculus can help derive the necessary coefficients. However, solving for the exponent n in such cases can be complex and may not yield a solution. Familiarity with these concepts will enhance the ability to use MATLAB effectively for data fitting.
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
cftool
 
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.
 

Similar threads

Replies
2
Views
3K
Replies
4
Views
1K
Replies
2
Views
3K
Replies
8
Views
2K
Replies
2
Views
1K
Replies
1
Views
2K
Replies
5
Views
2K
Back
Top