How to direct the variable in the genetic algorithm function to workspace function?
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Stephen23
2018-3-12
编辑:Stephen23
2018-3-12
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
2 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Genetic Algorithm 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!