You don't need to and definitelty should not use global variables for this. It is a very bad habit and inefficient to boot. Any time you think about using global
you should ask yourself if there is another way and search for it. It is only in the very very rare case that globals are needed/helpful (usually in large codebases such as toolboxes).
In your case, you should pass your ps
variable in as a parameter by creating an anonymous function. First define your cons
function like this so that it takes in a parameter argument:
function [c, ceq] = cons(x,ps)
Then create the anonymous function with one input (x
) and one captured parameter (the variable ps
, which needs to be defined before this):
[x, fval] = fmincon(@Obj,[1/3,1/3, 1/3],[],[],[],[],[],[],@(x)cons(x,ps));
Alternatively you can save a handle to the anonymous function and pass that in:
cfun = @(x)cons(x,ps);
[x, fval] = fmincon(@Obj,[1/3,1/3, 1/3],[],[],[],[],[],[],cfun);
Here's a blog post from The MathWorks with other bad habits.