Main Content

Optimize Live Editor Task withlsqlinSolver

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

The problem in this example is to find the point on the planex1+ 2x2+ 4x3= 7that is closest to the origin. The easiest way to solve this problem is to minimize the square of the distance from a pointx= (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 x 1 2 + x 2 2 + x 3 2 , you can describe the problem as follows:

min x f ( x ) = x 1 2 + x 2 2 + x 3 2 ,

subject to the constraint

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

The functionf(x) is theobjective functionandx1+ 2x2+ 4x3= 7is anequality constraint. More complicated problems might contain other equality constraints, inequality constraints, and upper or lower bound constraints.

Set Up and Solve the Problem UsingOptimize

Set up the problem with thelsqlinsolver in theOptimizeLive Editor task.

  1. Create a new live script by clicking theNew Live Scriptbutton in theFilesection on theHometab.

    New Live Script button

  2. Insert anOptimizeLive Editor task. Click theInserttab and then, in theCodesection, selectTask > Optimize.

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

  3. Click theSolver-basedbutton. TheOptimizetask opens.

  4. In theSpecify problem typesection of the task, selectObjective > Least squaresandConstraints > Linear equality.

    The task selectslsqlinas the recommended solver.

  5. To get the dataCanddinto the MATLAB®workspace, click theSection Breakbutton on theInserttab. 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 pressingCtrl+Enter. This places the variables into the workspace.

  8. In theSelect problem datasection 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 pressingCtrl+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 variablessolutionandobjectiveValueto the MATLAB workspace.

  11. 插入一段休息以下任务。将这些lines in the new section.

    disp(solution) disp(objectiveValue)
  12. Run the section by pressingCtrl+Enter.

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

See Also

|

Related Topics