Main Content

Optimize Live Editor Task with lsqlin Solver

This example shows how to use the Optimize Live Editor task to solve a constrained least-squares problem.

The problem in this example is to find the point on the plane x1 + 2x2 + 4x3 = 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 = (x1,x2,x3) on the plane to the origin, which returns the same optimal point as minimizing the actual distance. Because the square of the distance from an arbitrary point (x1,x2,x3) to the origin is x12+x22+x32, you can describe the problem as follows:


subject to the constraint

x1 + 2x2 + 4x3 = 7.(1)

The function f(x) is the objective function and x1 + 2x2 + 4x3 = 7 is an equality constraint. More complicated problems might contain other equality constraints, inequality constraints, and upper or lower bound constraints.

Set Up and Solve the Problem Using Optimize

Set up the problem with the lsqlin solver in the Optimize Live Editor task.

  1. Create a new live script by clicking the New Live Script button in the File section on the Home tab.

    New Live Script button

  2. Insert an Optimize Live Editor task. Click the Insert tab and then, in the Code section, select Task > Optimize.

    Optimize task in Live Editor: Choose between problem-based (recommended) and solver-based

  3. Click the Solver-based button. The Optimize task opens.

  4. In the Specify problem type section of the task, select Objective > Least squares and Constraints > Linear equality.

    The task selects lsqlin as the recommended solver.

  5. To get the data C and d into the MATLAB® workspace, click the Section Break button on the Insert tab. In the new section, enter the following code.

    C = eye(3);
    d = zeros(3,1);
  6. Set the linear equality constraint matrix and vector.

    Aeq = [1 2 4];
    beq = 7;
  7. Run the section by pressing Ctrl+Enter. This places the variables into the workspace.

  8. In the Select problem data section of the task, set the entries to their corresponding values.

    Variables C, d, Aeq, and beq are selected, and x0 is not

  9. Run the solver by pressing Ctrl+Enter. View the exit message.

    Exit message reports minimum found satisfying constraints

  10. To find the solution, look at the top of the task.

    Returned variables are solution and objectiveValue

    The solver returns the variables solution and objectiveValue to the MATLAB workspace.

  11. Insert a section break below the task. Place these lines in the new section.

  12. Run the section by pressing Ctrl+Enter.

    solution = [1/3, 2/3, 4/3]. objective = 7/3.

See Also


Related Topics