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.
Best Answer