[英]Optimization with genetic algorithm in matlab
I have written a simple optimization code using genetic algorithm.I don't know why I get error during running the code.Here is my code:我用遗传算法写了一个简单的优化代码。我不知道为什么我在运行代码时出错。这是我的代码:
f = @(x1,x2) 1-x1.^2+(x1-x2).^2;
A = [1 1;-1 2;2 1];
b =[2 2 3]' ;
Aeq = [];
beq = [];
Lb = [0 0]';
Ub = [];
[Xopt,Fval] = ga(f,2,A,b,Aeq,beq,Lb,Ub)
I don not know why matlab gives me error.I wrote this programm based on the "Genetic algorithm Documentation" bit still gives me error:我不知道为什么 matlab 给我错误。我根据“遗传算法文档”位编写了这个程序仍然给我错误:
Error using @(x1,x2)1-x1.^2+(x1-x2).^2
Not enough input arguments.
Error in createAnonymousFcn>@(x)fcn(x,FcnArgs{:}) (line 11)
fcn_handle = @(x) fcn(x,FcnArgs{:});
Error in makeState (line 48)
firstMemberScore = FitnessFcn(state.Population(initScoreProvided+1,:));
Error in galincon (line 18)
state = makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);
Error in ga (line 351)
[x,fval,exitFlag,output,population,scores] = galincon(FitnessFcn,nvars, ...
Caused by:
Failure in initial user-supplied fitness function evaluation. GA cannot continue
Objective functions of all optimization methods in MATLAB only accept 1 argument. MATLAB 中所有优化方法的目标函数只接受 1 个参数。 According to ga documents :根据ga 文件:
fun — Objective function fun - 目标函数
Objective function, specified as a function handle or function name.目标函数,指定为函数句柄或函数名称。 Write the objective function to accept a row vector of length
nvars
and return a scalar value.编写目标函数以接受长度为nvars
的行向量并返回一个标量值。When the 'UseVectorized' option is true, write fun to accept a pop-by-nvars matrix, where pop is the current population size.当 'UseVectorized' 选项为 true 时,编写 fun 以接受 pop-by-nvars 矩阵,其中 pop 是当前人口规模。 In this case, fun returns a vector the same length as pop containing the fitness function values.在这种情况下, fun 返回一个与包含适应度函数值的 pop 长度相同的向量。 Ensure that fun does not assume any particular size for pop, since ga can pass a single member of a population even in a vectorized calculation.确保 fun 不为 pop 假定任何特定大小,因为即使在矢量化计算中,ga 也可以传递总体中的单个成员。
Change you objective function and it should work:改变你的目标函数,它应该可以工作:
f = @(x) 1-x(1).^2+(x(1)-x(2)).^2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.