x0s = [ones(1, i), 10 * ones(1, n-i)]; results = cell(size(x0s)); for i = 1:numel(x0s) x0 = x0s{i}; lb = ones(1, n); ub = 10 * ones(1, n); Aeq = ones(1, n); Beq = mean(x0); A = []; b = []; nonlcon = @nonlinear_constraints; options = optimoptions('fmincon', 'Display', 'off'); results{i} = fmincon(@objective_function, x0, A, b, Aeq, Beq, lb, ub, nonlcon, options); end这段代码会报错函数或变量 'i' 无法识别,怎么修改
时间: 2023-07-15 22:10:54 浏览: 93
I=trapesium(x0,x1,n):梯形程序-matlab开发
这个错误是因为在 MATLAB 中,匿名函数中不支持使用 for 循环中的变量,例如 i。解决这个问题可以使用一个临时变量 j 来替代 i,如下所示:
```
x0s = [ones(1, j), 10 * ones(1, n-j)];
results = cell(size(x0s));
for j = 1:numel(x0s)
x0 = x0s{j};
lb = ones(1, n);
ub = 10 * ones(1, n);
Aeq = ones(1, n);
Beq = mean(x0);
A = [];
b = [];
nonlcon = @nonlinear_constraints;
options = optimoptions('fmincon', 'Display', 'off');
results{j} = fmincon(@objective_function, x0, A, b, Aeq, Beq, lb, ub, nonlcon, options);
end
```
这样就可以解决该问题。
阅读全文