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 + b
where a
and b
are 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 a
and 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 a
and b
it 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…