Main Content

到平面的最短距离

问题

此示例说明如何使用基于问题的方法来表示线性最小二乘问题。

问题是找出从原点(点 [0,0,0])到平面 x1+2x2+4x3=7 的最短距离。换句话说,此问题就是在约束 x1+2x2+4x3=7 下最小化 f(x)=x12+x22+x32。函数 f(x) 称为目标函数x1+2x2+4x3=7等式约束。更复杂的问题可能包含其他等式约束、不等式约束以及上界或下界约束。

设置问题

为了使用基于问题的方法来表示此问题,请创建一个名为 pointtoplane 的优化问题对象。

pointtoplane = optimproblem;

创建一个问题变量 x 作为一个具有三个分量的连续变量。

x = optimvar('x',3);

创建目标函数,并将其放入 pointtoplaneObjective 属性中。

obj = sum(x.^2);
pointtoplane.Objective = obj;

创建线性约束并将其放入问题中。

v = [1,2,4];
pointtoplane.Constraints = dot(x,v) == 7;

问题表示已完成。要检查错误,请审核问题。

show(pointtoplane)
  OptimizationProblem : 

	Solve for:
       x

	minimize :
       sum(x.^2)


	subject to :
       x(1) + 2*x(2) + 4*x(3) == 7
     

公式是正确的。

求解问题

通过调用 solve 求解问题。

[sol,fval,exitflag,output] = solve(pointtoplane);
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.
disp(sol.x)
    0.3333
    0.6667
    1.3333

验证解

要验证解,请通过解析法求解问题。前面提到,对于任何非零的 t,向量 t*[1,2,4] = t*v 垂直于平面 x1+2x2+4x3=7。因此满足方程 dot(t*v,v) = 7t 的值的解点 xoptt*v

t = 7/dot(v,v)
t = 0.3333
xopt = t*v
xopt = 1×3

    0.3333    0.6667    1.3333

实际上,向量 xopt 等效于 solve 找到的点 sol.x

相关主题