原始代码
%调用遗传算法 ga() 函数解决优化问题
nvars = 1;
A = -2;
b = -1;
syms x
fitnessfcn_x = x^2 - 2*x;
[x_optimal, f_optimal] = ga(fitnessfcn_x,nvars, A, b, [], []); %matlab自带函数
运行报错
Fitness function must be a function handle.
解决方法
创建函数句柄,方法参见此处。
%通过添加@(x)创建函数句柄
%fitnessfcn_x = x^2 - 2*x;
fitnessfcn_x = @(x)x^2 - 2*x;