Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

matlab - Curve fitting without toolbox

Without the curve fit toolbox how do you fit a function to data in MATLAB?

In particular, how do you fit a function that isn't a polynomial, e.g., if I want to fit a function like y = x^(1/3) + 5 where it is not an integer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you know the form of the function you want to fit but do not know its parameters, you can use fminsearch to find the parameters that would fit your data. If you have data (possibly noisy) that you want to fit to y=x^a + bwhere aand bare unknown (here I will assume that the true values are a=1/3 and b=5) this is how I'd have a quick answer:

Here I generate my data (you would not have to do that in a real life case)

>> x = linspace(0,5,10);
>> y = x.^(1/3) + 5;
>> y_noisy = y + 0.1*rand(size(y)); 

Then I define the function I want to minimize with respect to a and b and minimize it with fminsearch. In this case, I minimize the integral of the square of the difference between my data and the function used for the fit. Below I have defined two functions, one with the noisy data, and one without noise. You see that in the absence of noise you recover exactly the values of aand b.

NB: fminsearch wotks with a vector of parameters (v in my case). I took a=v(1)and b=v(2). You also have to provide some initial guess for v(here [1 1]).

>> err_noisy  = @(v) trapz(x,(y_noisy - x.^v(1)-v(2)).^2);
>> err = @(v) trapz(x,(y - x.^v(1)-v(2)).^2); 
>> v_noisy = fminsearch(err_noisy,[1 1])

v_noisy =

    0.3345    5.0594

>> v = fminsearch(err,[1 1])

v =

    0.3333    5.0000

Last comment, in cases where you have constraints on the values of aand bit is sometimes useful to perform some change of variable. For example if you know that a>0, you might want to identify log(a) and then convert the identified value to a.

Hope this helps.

A.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...