MATLAB: How to direct the variable in the genetic algorithm function to workspace function

function handlergenetic algorithm

variable1 = input('Variable 1: ');
variable2 = input('Variable 2: ');
variable3 = input('Variable 3: ');
variable4 = input('Variable 4: ');
function y = myfunc(x)
y = x(1)*variable1 + x(2)*variable 2
function [c,ceq] = constraint(x)
c = [x(1)+x(2)-variable3;x(1)*x(2)-variable4];
ceq = [];
ObjectiveFunction = @myfunc;
nvars = 2; % Number of variables
LB = [0 0]; % Lower bound
UB = [100 100]; % Upper bound
ConstraintFunction = @constraint;
[x,fval] = ga(ObjectiveFunction,nvars,[],[],[],[],LB,UB,ConstraintFunction);
As shown in the code above, I am trying to optimize the objective function based on some inputs from user. However, the function handler does not permit the variable from workspace direct to the function even their name is same. Is there any solution for this case?

Best Answer

You need to parameterize the objective function, which can be achieved either using an anonymous function or nested functions:
Method one: nested functions: you could do something like this:
function [x,fval] = myga(v1,v2,v3,v4,LB,UB)
[x,fval] = ga(@myfunc,2,[],[],[],[],LB,UB,@constraint);
function y = myfunc(x)
y = x(1)*v1 + x(2)*v2;
end
function [c,ceq] = constraint(x)
c = [x(1)+x(2)-v3;x(1)*x(2)-v4];
ceq = [];
end
end
and call it like this:
var1 = str2double(input('Variable 1: ','s'));
var2 = str2double(input('Variable 2: ','s'));
var3 = str2double(input('Variable 3: ','s'));
var4 = str2double(input('Variable 4: ','s'));
[x,fval] = myga(var1,var2,var3,var4,[0,0],[100,100])
Method two: anonymous functions: you could do this (with version R2016b or later, where functions may be defined at the end of a script):
var1 = str2double(input('Variable 1: ','s'));
var2 = str2double(input('Variable 2: ','s'));
var3 = str2double(input('Variable 3: ','s'));
var4 = str2double(input('Variable 4: ','s'));
LB = [0,0];
UB = [100,100];
objfun = @(x)myfunc(x,var1,var2);
confun = @(x)constraint(x,var3,var4);
[x,fval] = ga(objfun,2,[],[],[],[],LB,UB,confun);
function y = myfunc(x,v1,v2)
y = x(1)*v1 + x(2)*v2;
end
function [c,ceq] = constraint(x,v3,v4)
c = [x(1)+x(2)-v3;x(1)*x(2)-v4];
ceq = [];
end