You need to parameterize the objective function, which can be achieved either using an anonymous function or nested functions:
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
Best Answer