Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Fit a Curve with Constrained Parameters

For a (x,y) dataset, let have a curve given by an expression in a, b,c... etc, such as f='a*exp(b*x)+c', to be fitted as cfit=fit(x,y,f).

Suppose we have a set of constraint such as b>0, c+b>a/2. How should i use the fit command in this case?.

like image 478
Brethlosze Avatar asked Jan 03 '23 11:01

Brethlosze


1 Answers

While you could set a lower boundary to enforce b>0, I don't think it is somehow possible to properly enforce c+b>a/2 with fit(). But ultimately every fitting problem can also be regarded as a "minimize the distance from the curve to the data" problem, so fmincon() can be used to achieve your goal:

%some sample x values
xdata = rand(1000,1);
%some parameters a,b,c
a = 2;
b = 3;
c = 4;
%resulting y values + some noise
ydata=a*exp(b*xdata)+c+rand(1000,1)*10-5;
plot(xdata,ydata,'o')

%function to minimize. It returns the sum of squared distances between the polynom and the data.
fun = @(coefs) sum((coefs(1)*exp(coefs(2).*xdata)+coefs(3)-ydata).^2);
%nonlinear constaint to enforce c+b>a/2, which is the same as -(c+b-a/2)<0
nonlcon = @(coefs)deal(-(coefs(3)+coefs(2)-coefs(1)/2), 0);
% lower bounds to enforce b>0
lb = [-inf 0 -inf];
%starting values
x0 = [1 1 1];
%finally find the coefficients (which should approximately be the values of a, b and c)
coefs = fmincon(fun,x0,[],[],[],[],lb,[],nonlcon)
like image 67
Leander Moesinger Avatar answered Jan 11 '23 10:01

Leander Moesinger