在基于问题的方法中传递额外的参数
在优化问题中,有时目标函数或约束函数包含除了自变量之外的参数。额外的参数可以是数据,也可以表示在优化过程中不变的变量。
要在基于问题的方法中包含这些参数,只需在目标函数或约束函数中引用工作区变量即可。
传递数据的最小二乘问题
例如,假设 particle.mat
文件中有矩阵 C
和 d
,这些矩阵表示您的问题的数据。将数据加载到您的工作区中。
load particle
查看矩阵的大小。
disp(size(C))
2000 400
disp(size(d))
2000 1
创建一个大小适合形成向量 C*x
的优化变量 x
。
x = optimvar('x',size(C,2));
创建一个优化问题,使 C*x – d
中的项的平方和最小,并满足 x
为非负值的约束。
x.LowerBound = 0; prob = optimproblem; expr = sum((C*x - d).^2); prob.Objective = expr;
只要在目标函数表达式中引用数据 C
和 d
,就可以将它们包含在问题中。求解。
[sol,fval,exitflag,output] = solve(prob)
Solving problem using lsqlin. Minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
sol = struct with fields:
x: [400x1 double]
fval = 22.5795
exitflag = OptimalSolution
output = struct with fields:
message: 'Minimum found that satisfies the constraints....'
algorithm: 'interior-point'
firstorderopt: 9.9673e-07
constrviolation: 0
iterations: 9
linearsolver: 'sparse'
cgiterations: []
solver: 'lsqlin'
具有额外参数的非线性问题
对非线性问题使用同样的方法。例如,假设您有一个包含多个变量的目标函数,其中一些变量是用于优化的固定数据。
type parameterfun
function y = parameterfun(x,a,b,c) y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2) + (-c + c*x(2)^2)*x(2)^2;
对于此目标函数,x
是二元素向量,a
、b
和 c
是标量参数。创建优化变量,并在工作区中对参数赋值。
a = 4;
b = 2.1;
c = 4;
x = optimvar('x',2);
创建一个优化问题。由于此目标函数是 x
的有理函数,您可以根据优化变量来指定目标。从 x0.x = [1/2;1/2]
点开始求解问题。
prob = optimproblem; prob.Objective = parameterfun(x,a,b,c); x0.x = [1/2;1/2]; [sol,fval] = solve(prob,x0)
Solving problem using fminunc. Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
sol = struct with fields:
x: [2x1 double]
fval = -1.0316
如果 parameterfun
不是由支持的函数组成的,您可以将 parameterfun
转换为优化表达式,并将转换后的表达式设置为目标。请参阅Supported Operations for Optimization Variables and Expressions和将非线性函数转换为优化表达式。
expr = fcn2optimexpr(@parameterfun,x,a,b,c); prob.Objective = expr; [sol,fval] = solve(prob,x0)
Solving problem using fminunc. Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
sol = struct with fields:
x: [2x1 double]
fval = -1.0316
Copyright 2018–2020 The MathWorks, Inc.