This example shows how to use the Optimization app to solve a constrained least-squares problem.

The Optimization app warns that it will be removed in a future release.

The problem in this example is to find the point on the plane *x*_{1} + 2*x*_{2} + 4*x*_{3} = 7 that is closest
to the origin. The easiest way to solve this problem is to minimize
the square of the distance from a point *x* = (*x*_{1},*x*_{2},*x*_{3}) on
the plane to the origin, which returns the same optimal point as minimizing
the actual distance. Since the square of the distance from an arbitrary
point (*x*_{1},*x*_{2},*x*_{3}) to
the origin is $${x}_{1}^{2}+{x}_{2}^{2}+{x}_{3}^{2}$$, you can describe
the problem as follows:

$$\underset{x}{\mathrm{min}}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.

This section shows how to set up the problem with the `lsqlin`

solver
in the Optimization app.

Enter

`optimtool`

in the Command Window to open the Optimization app.Select

`lsqlin`

from the selection of solvers. Use the`Interior point`

algorithm.Enter the following to create variables for the objective function:

In the

**C**field, enter`eye(3)`

.In the

**d**field, enter`zeros(3,1)`

.

The

**C**and**d**fields should appear as shown in the following figure.Enter the following to create variables for the equality constraints:

In the

**Aeq**field, enter`[1 2 4]`

.In the

**beq**field, enter`7`

.

The

**Aeq**and**beq**fields should appear as shown in the following figure.Click the

**Start**button as shown in the following figure.When the algorithm terminates, under

**Run solver and view results**the following information is displayed:The

**Current iteration**value when the algorithm terminated, which for this example is`1`

.The final value of the objective function when the algorithm terminated:

Objective function value: 2.333333333333334

The exit message:

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.

The final point, which for this example is

0.333 0.667 1.333