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');
