MATLAB: How to use anonymous function in non-linear constraints in fmincon

anonymous functionsfminconMATLABnon linear constraintsoptimization

Hi everyone.
I'm facing some issues in the use of fmincon. I'd like to know if there is a way to express the non-linear inequality and/or equality constraints without defining a function (.m file), but using for instance a similar syntax to the one that we use for the function that we want to minimize. Something like this "fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2", but for the constraint.
I need it since some of the constants which appear in my constraint function should be computed by other code and are not simply numbers which I can fix before running my code. However, as far as I remember, functions do not see the workspace, so that if I call a variable from my workspace in my function, it will not work.
My hope is that by employing an anonymous function to express the constraints ( c and ceq according to help document for fmincon), I'll be able to call parameters from the workspace in the anonymous function.
Last thing, if I try to use an anonymous function, I don't manage to deal with double outputs and I get the following error:
Error using fmincon (line 625)
The constraint function must return two outputs; the nonlinear inequality constraints and the nonlinear equality constraints.
I hope I've been clear,
thanks in advance
Roberto

Best Answer

Yes, you could write an anonymous function as your nonlinear constraint function as long as your constraints are simple enough.
f = @(x) deal(x.^2, x.^3);
[a, b] = f(1:5)
However, I'm not sure that's going to achieve your end goal. "I need it since some of the constants which appear in my constraint function should be computed by other code and are not simply numbers which I can fix before running my code." In that case you may want to consider nested functions. Define the shared variable in the main function and nest the nonlinear constraint and whatever other functions need access to that shared variable inside the main function. Adapting one of the examples on that page to illustrate what I mean:
function y = findzero(b,c,x0)
t = 0;
[y, ~, ~, out] = fzero(@poly,x0);
fprintf('FZERO called poly %d times according to t.\n', t);
fprintf('FZERO called poly %d times according to out.\n',out.funcCount);
function y = poly(x)
y = x^3 + b*x + c;
t = t + 1;
fprintf('t = %d, x = %f, y = %f\n', t, x, y);
end
end
The poly function nested inside findzero has access to the b, c, and t variables defined inside findzero. It only reads from b and c, but it both reads from and writes to t.