Matlab - Adjust a curve with limited parameters

For the data set ( x, y), even if there is a curve defined by the expression in a, b, c... etc., for example f='a*exp(b*x)+c', which must be installed cfit=fit(x,y,f).

Suppose we have a set of constraints, such as b>0, c+b>a/2. How should I use the command fitin this case?

+4
source share
3 answers

For constraints that are only numeric values, for example b > 0, you can use 'Lower'and 'Upper'constrain arguments to indicate them. For more complex relationships, such as c+b>a/2, you have to use an approach like James suggests , setting the function output to a high value, for example flintmax, to create a big mistake. For example, suppose I define my function as follows:

function y = my_fcn(a, b, c, x)
  if (c+b > a/2)
    y = a.*exp(b.*x)+c;
  else
    y = flintmax().*ones(size(x));
  end
end

I can create a set of noisy test data as follows:

a = 4;
b = 2;
c = 1;
x = (0:0.01:2).';
y = my_fcn(a, b, c, x) + 40.*(rand(size(x))-0.5);

And then set the curve (note that you must use an anonymous function as the function descriptor will not work for any reason):

params = fit(x, y, @(a, b, c, x) my_fcn(a, b, c, x), ...
             'StartPoint', [1 1 1], ...  % Starting guesses for [a b c]
             'Lower', [-Inf 0 -Inf]);    % Set bound for 'b'

params = 

     General model:
     params(x) = my_fcn(a,b,c,x)
     Coefficients (with 95% confidence bounds):
       a =       4.297  (2.985, 5.609)
       b =       1.958  (1.802, 2.113)
       c =      0.1908  (-4.061, 4.442)

, , - . :

plot(x, y);
hold on;
plot(x, my_fcn(params.a, params.b, params.c, x), 'r');

enter image description here

+3

b>0, , - c+b>a/2 fit(). " ", fmincon() :

%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)
+4

One simplified method is to have the function installed that returns a very large value, which leads to a very large error if the parameter values ​​are outside the limits. This “brick wall” method is not optimal and will cause problems when the set parameter values ​​are close to the boundary conditions. It is worth a try because it is quickly implemented and can work in simple cases. Try to start with the initial parameter values ​​within the boundaries.

+2
source

Source: https://habr.com/ru/post/1685532/


All Articles