Main Content

fcn2optimexpr

Convert function to optimization expression

Description

example

[out1,out2,...,outN] = fcn2optimexpr(fcn,in1,in2,...,inK)converts the functionfcn(in1,in2,...,inK)to an optimization expression withNoutputs.

example

[out1,out2,...,outN] = fcn2optimexpr(fcn,in1,in2,...,inK,Name,Value)specifies additional options using one or more name-value pair arguments. For example, you can save a function evaluation by passingOutputSize.

Examples

collapse all

To use a MATLAB™ function in the problem-based approach when it is not composed of supported functions, first convert it to an optimization expression. SeeSupported Operations for Optimization Variables and Expressionsand将非线性函数优化表达ion.

To use the objective functiongamma(the mathematical function Γ ( x ) , an extension of the factorial function), create an optimization variablexand use it in a converted anonymous function.

x = optimvar('x'); obj = fcn2optimexpr(@gamma,x); prob = optimproblem('Objective',obj); show(prob)
OptimizationProblem : Solve for: x minimize : gamma(x)

To solve the resulting problem, give an initial point structure and callsolve.

x0.x = 1/2; sol = solve(prob,x0)
Solving problem using fminunc. Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
sol =struct with fields:x: 1.4616

For more complex functions, convert a function file. The function filegammabrock.mcomputes an objective of two optimization variables.

typegammabrock
function f = gammabrock(x,y) f = (10*(y - gamma(x)))^2 + (1 - x)^2;

Include this objective in a problem.

x = optimvar('x','LowerBound',0); y = optimvar('y'); obj = fcn2optimexpr(@gammabrock,x,y); prob = optimproblem('Objective',obj); show(prob)
OptimizationProblem : Solve for: x, y minimize : gammabrock(x, y) variable bounds: 0 <= x

Thegammabrockfunction is a sum of squares. You get a more efficient problem formulation by expressing the function as an explicit sum of squares of optimization expressions.

f = fcn2optimexpr(@(x,y)y - gamma(x),x,y); obj2 = (10*f)^2 + (1-x)^2; prob2 = optimproblem('Objective',obj2);

To see the difference in efficiency, solveprobandprob2并检查iterat数量的差异ions.

x0.x = 1/2; x0.y = 1/2; [sol,fval,~,output] = solve(prob,x0);
使用fmincon解决问题。发现局部最小值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.
[sol2,fval2,~,output2] = solve(prob2,x0);
Solving problem using lsqnonlin. Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
fprintf('prob took %d iterations, but prob2 took %d iterations\n',output.iterations,output2.iterations)
prob took 21 iterations, but prob2 took 2 iterations

If your function has several outputs, you can use them as elements of the objective function. In this case,uis a 2-by-2 variable,vis a 2-by-1 variable, andexpfn3has three outputs.

typeexpfn3
function [f,g,mineval] = expfn3(u,v) mineval = min(eig(u)); f = v'*u*v; f = -exp(-f); t = u*v; g = t'*t + sum(t) - 3;

Create appropriately sized optimization variables, and create an objective function from the first two outputs.

u = optimvar('u',2,2); v = optimvar('v',2); [f,g,mineval] = fcn2optimexpr(@expfn3,u,v); prob = optimproblem; prob.Objective = f*g/(1 + f^2); show(prob)
OptimizationProblem : Solve for: u, v minimize : ((arg2 .* arg3) ./ (1 + arg1.^2)) where: [arg1,~,~] = expfn3(u, v); [arg2,~,~] = expfn3(u, v); [~,arg3,~] = expfn3(u, v);

You can use theminevaloutput in a subsequent constraint expression.

In problem-based optimization, constraints are two optimization expressions with a comparison operator (==,<=, or>=) between them. You can usefcn2optimexprto create one or both optimization expressions. See将非线性函数优化表达ion.

Create the nonlinear constraint thatgammafn2is less than or equal to –1/2. This function of two variables is in thegammafn2.mfile.

typegammafn2
function f = gammafn2(x,y) f = -gamma(x)*(y/(1+y^2));

Create optimization variables, convert the function file to an optimization expression, and then express the constraint asconfn.

x = optimvar('x','LowerBound',0); y = optimvar('y','LowerBound',0); expr1 = fcn2optimexpr(@gammafn2,x,y); confn = expr1 <= -1/2; show(confn)
gammafn2(x, y) <= -0.5

Create another constraint thatgammafn2is greater than or equal tox + y.

confn2 = expr1 >= x + y;

Create an optimization problem and place the constraints in the problem.

prob = optimproblem; prob.Constraints.confn = confn; prob.Constraints.confn2 = confn2; show(prob)
OptimizationProblem : Solve for: x, y minimize : subject to confn: gammafn2(x, y) <= -0.5 subject to confn2: gammafn2(x, y) >= (x + y) variable bounds: 0 <= x 0 <= y

If your problem involves a common, time-consuming function to compute the objective and nonlinear constraint, you can save time by using theReuseEvaluationname-value argument. Therosenbrocknormfunction computes both the Rosenbrock objective function and the norm of the argument for use in the constraint x 2 4 .

typerosenbrocknorm
function [f,c] = rosenbrocknorm(x) pause(1) % Simulates time-consuming function c = dot(x,x); f = 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;

Create a 2-D optimization variablex. Then convertrosenbrocknormto an optimization expression by usingfcn2optimexprand set theReuseEvaluationname-value argument totrue. To ensure thatfcn2optimexprkeeps thepausestatement, set theAnalysisname-value argument to 'off'.

x = optimvar('x',2); [f,c] = fcn2optimexpr(@rosenbrocknorm,x,...'ReuseEvaluation',true,'Analysis','off');

Create objective and constraint expressions from the returned expressions. Include the objective and constraint expressions in an optimization problem. Review the problem usingshow.

prob = optimproblem('Objective',f); prob.Constraints.cineq = c <= 4; show(prob)
OptimizationProblem : Solve for: x minimize : [argout,~] = rosenbrocknorm(x) subject to cineq: arg_LHS <= 4 where: [~,arg_LHS] = rosenbrocknorm(x);

Solve the problem starting from the initial pointx0.x = [-1;1], timing the result.

x0.x = [-1;1]; tic [sol,fval,exitflag,output] = solve(prob,x0)
使用fmincon解决问题。发现局部最小值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. 
sol =struct with fields:x: [2×1 double]
fval = 4.5793e-11
exitflag = OptimalSolution
output =struct with fields:iterations: 44 funcCount: 164 constrviolation: 0 stepsize: 4.3124e-08 algorithm: 'interior-point' firstorderopt: 5.1691e-07 cgiterations: 10 message: 'Local 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.↵↵↵↵Optimization completed: The relative first-order optimality measure, 5.169074e-07,↵is less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint↵violation, 0.000000e+00, is less than options.ConstraintTolerance = 1.000000e-06.' bestfeasible: [1×1 struct] objectivederivative: "finite-differences" constraintderivative: "finite-differences" solver: 'fmincon'
toc
Elapsed time is 165.623157 seconds.

The solution time in seconds is nearly the same as the number of function evaluations. This result indicates that the solver reused function values, and did not waste time by reevaluating the same point twice.

For a more extensive example, seeObjective and Constraints Having a Common Function in Serial or Parallel, Problem-Based. For more information on usingfcn2optimexpr, see将非线性函数优化表达ion.

Input Arguments

collapse all

Function to convert, specified as a function handle.

Example:@sinspecifies the sine function.

Data Types:function_handle

Input argument, specified as a MATLAB variable. The input can have any data type and any size. You can include any problem variables or data in the input argumentin; seePass Extra Parameters in Problem-Based Approach.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64|logical|char|string|struct|table|cell|function_handle|categorical|datetime|duration|calendarDuration|fi
Complex Number Support:Yes

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and encloseNamein quotes.

Example:[out1,out2] = fcn2optimexpr(@fun,x,y,'OutputSize',[1,1],'ReuseEvaluation',true)specifies thatout1andout2are scalars that a solver will reuse between objective and constraint functions without recalculation.

Indication to analyze the functionfcnto determine whether it consists entirely of supported operations (seeSupported Operations for Optimization Variables and Expressions), specified as"on"or"off".

  • If you wantfcn2optimexprto analyzefcnand, if possible, use the supported operations to implementfcn, specify"on". This specification enablesfcnto use automatic differentiation and to choose an appropriate solver as described inSolver.

  • If you do not wantfcn2optimexprto analyzefcnand, therefore, to treatfcnas a black box without automatic differentiation, specify"off". In this case,solveuses onlyfmincon,fminunc, orlsqnonlinas the solver.

For more information about the effects ofAnalysis, seeLimitations.

Example:[out1,out2] = fcn2optimexpr(@fun,x,"Analysis","off")

Data Types:char|string

报告function analysis details, specified as"off"(do not report) or"on"(report). IfAnalysisis"off", there is nothing to report.

Example:[out1,out2] = fcn2optimexpr(@fun,x,"Display","on")

Data Types:char|string

Size of the output expressions, specified as:

  • An integer vector — If the function has one outputout1,OutputSizespecifies the size ofout1. If the function has multiple outputsout1,…,outN,OutputSizespecifies that all outputs have the same size.

  • A cell array of integer vectors — The size of outputoutj is the jth element ofOutputSize.

Note

A scalar has size[1,1].

If you do not specify the'OutputSize'name-value pair argument, thenfcn2optimexprpasses data tofcnin order to determine the size of the outputs (seeAlgorithms). By specifying'OutputSize', you enablefcn2optimexprto skip this step, which saves time. Also, if you do not specify'OutputSize'and the evaluation offcnfails for any reason, thenfcn2optimexprfails as well.

Example:[out1,out2,out3] = fcn2optimexpr(@fun,x,'OutputSize',[1,1])specifies that the three outputs[out1,out2,out3]are scalars.

Example:[out1,out2] = fcn2optimexpr(@fun,x,'OutputSize',{[4,4],[3,5]})specifies thatout1has size 4-by-4 andout2has size 3-by-5.

Data Types:double|cell

Indicator to reuse values, specified asfalse(do not reuse) ortrue(reuse).

Note

ReuseEvaluationmay not have an effect whenAnalysis="on".

ReuseEvaluationcan make your problem run faster when, for example, the objective and some nonlinear constraints rely on a common calculation. In this case, the solver stores the value for reuse wherever needed and avoids recalculating the value.

Reusable values involve some overhead, so it is best to enable reusable values only for expressions that share a value.

Example:[out1,out2,out3] = fcn2optimexpr(@fun,x,"ReuseEvaluation",true,"Analysis","off")allowsout1,out2, andout3to be used in multiple computations, with the outputs being calculated only once per evaluation point.

Data Types:logical

Output Arguments

collapse all

Output argument, returned as anOptimizationExpression. The size of the expression depends on the input function.

Limitations

AnalysisCan Ignore Noncomputational Functions

  • TheAnalysisalgorithm might not include noncomputational functions. This aspect of the algorithm can result in the following:

    • pausestatements are ignored.

    • A global variable that does not affect the results can be ignored. For example, if you use a global variable, for example, to count how many times the function runs, then you might obtain a misleading count.

    • If the function contains a call torandorrng, the function might execute the first call only, and future calls do not set the random number stream.

    • Aplotcall might not update a figure at all iterations.

    • Saving data to amatfile or text file might not occur at every iteration.

  • To ensure that noncomputational functions operate as you expect, set theAnalysisname-value argument to"off".

Algorithms

To find the output size of each returned expression when you do not specifyOutputSize,fcn2optimexprevaluates the function at the following point for each element of the problem variables.

Variable Characteristics Evaluation Point
Finite upper bounduband finite lower boundlb (lb + ub)/2 + ((ub - lb)/2)*eps
Finite lower bound and no upper bound lb + max(1,abs(lb))*eps
Finite upper bound and no lower bound ub - max(1,abs(ub))*eps
是没有界限的 1 + eps
Variable is specified as an integer floorof the point given previously

An evaluation point might lead to an error in function evaluation. To avoid this error, specify 'OutputSize'.

Version History

Introduced in R2019a