필터 지우기
필터 지우기

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

조회 수: 5 (최근 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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Genetic Algorithm에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by