Optimize Live Editor Task withlsqlin
Solver
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 , you can describe the problem as follows:
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 thelsqlin
solver in theOptimizeLive Editor task.
Create a new live script by clicking theNew Live Scriptbutton in theFilesection on theHometab.
Insert anOptimizeLive Editor task. Click theInserttab and then, in theCodesection, selectTask > Optimize.
Click theSolver-basedbutton. TheOptimizetask opens.
In theSpecify problem typesection of the task, selectObjective > Least squaresandConstraints > Linear equality.
The task selects
lsqlin
as the recommended solver.To get the data
C
andd
into the MATLAB®workspace, click theSection Breakbutton on theInserttab. In the new section, enter the following code.C = eye(3); d = zeros(3,1);
Set the linear equality constraint matrix and vector.
Aeq = [1 2 4]; beq = 7;
Run the section by pressingCtrl+Enter. This places the variables into the workspace.
In theSelect problem datasection of the task, set the entries to their corresponding values.
Run the solver by pressingCtrl+Enter. View the exit message.
To find the solution, look at the top of the task.
The solver returns the variables
solution
andobjectiveValue
to the MATLAB workspace.插入一段休息以下任务。将这些lines in the new section.
disp(solution) disp(objectiveValue)
Run the section by pressingCtrl+Enter.