MATLAB: Error using GA in MATLAB for nonlinear constrained optimization

genetic algorithmGlobal Optimization ToolboxoptimizationRobust Control Toolbox

I am using GA in MATLAB to minimize a convex function. I am getting the following error,
Error using constrValidate (line 59)
Constraint function must return real value.
But when in the cost.m the system called "sys" is created (which is a global variable), then the constr function computes its H_\infty norm which is a real value. Still I don't understand why I am getting this error.
My codes are attached.
Any help is really appreciated.
Thanks

Best Answer

constr.m is receiving an empty sys which leads to hinfnorm warning and returning infinity.
sys is empty because it is a global variable that has not been initialized.
sys has not been initialized at that point because the cost function has not yet been called.
It is permitted for ga to invoke the constraint function before the cost function, as ga wants to be sure that the proposed points are valid before bothering to calculate their cost.
Your cost function needs to calculate sys as well.
If you have a more recent version, you could consider moving the calculation of sys into a function with k as input, and memoizing the function, https://www.mathworks.com/help/matlab/ref/memoize.html