How to direct the variable in the genetic algorithm function to workspace function?

2 ビュー (過去 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?

採用された回答

Stephen23
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:
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
  2 件のコメント
Walter Roberson
Walter Roberson 2018 年 3 月 12 日
You need to do this for the nonlinear constraint function too.
Soon Kok Yew
Soon Kok Yew 2018 年 3 月 13 日
Works well! Thanks alot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGenetic Algorithm についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by