Main Content

This example shows how to formulate a linear least squares problem using the problem-based approach.

The problem is to find the shortest distance from the origin (the point `[0,0,0]`

) to the plane $${x}_{1}+2{x}_{2}+4{x}_{3}=7$$. In other words, this problem is to minimize $$f(x)={x}_{1}^{2}+{x}_{2}^{2}+{x}_{3}^{2}$$ subject to the constraint $${x}_{1}+2{x}_{2}+4{x}_{3}=7$$. The function *f*(*x*) is called the *objective function* and $${x}_{1}+2{x}_{2}+4{x}_{3}=7$$ is an *equality constraint*. More complicated problems might contain other equality constraints, inequality constraints, and upper or lower bound constraints.

To formulate this problem using the problem-based approach, create an optimization problem object called `pointtoplane`

.

pointtoplane = optimproblem;

Create a problem variable `x`

as a continuous variable with three components.

`x = optimvar('x',3);`

Create the objective function and put it in the `Objective`

property of `pointtoplane`

.

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

Create the linear constraint and put it in the problem.

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

The problem formulation is complete. To check for errors, review the problem.

show(pointtoplane)

OptimizationProblem : Solve for: x minimize : sum(x.^2) subject to : x(1) + 2*x(2) + 4*x(3) == 7

The formulation is correct.

Solve the problem by calling `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

To verify the solution, solve the problem analytically. Recall that for any nonzero `t`

, the vector `t*[1,2,4] = t*v`

is perpendicular to the plane $${x}_{1}+2{x}_{2}+4{x}_{3}=7$$. So the solution point `xopt`

is `t*v`

for the value of `t`

that satisfies the equation `dot(t*v,v) = 7`

.

t = 7/dot(v,v)

t = 0.3333

xopt = t*v

`xopt = `*1×3*
0.3333 0.6667 1.3333

Indeed, the vector `xopt`

is equivalent to the point `sol.x`

that `solve`

finds.