To use a MATLAB™ function in the problem-based approach, first convert it to an optimization expression.

To use the objective function `gamma`

(the mathematical function $$\Gamma (x)$$, an extension of the factorial function), create an optimization variable `x`

and use it in a converted anonymous function.

OptimizationProblem :
Solve for:
x
minimize :
gamma(x)

To solve the resulting problem, give an initial point structure and call `solve`

.

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 file `gammabrock.m`

computes an objective of two optimization variables.

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

Include this objective in a problem.

OptimizationProblem :
Solve for:
x, y
minimize :
gammabrock(x, y)
variable bounds:
0 <= x

The `gammabrock`

function 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.

To see the difference in efficiency, solve `prob`

and `prob2`

and examine the differences in number of iterations.

Solving problem using fmincon.
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.

Solving problem using lsqnonlin.
Local minimum found.
Optimization completed because the size of the gradient is less than
the value of the optimality tolerance.

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, `u`

is a 2-by-2 variable, `v`

is a 2-by-1 variable, and `expfn3`

has three outputs.

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.

OptimizationProblem :
Solve for:
u, v
minimize :
((arg3 .* arg4) ./ (1 + arg2.^2))
where:
[arg2,~,~] = expfn3(u, v);
[arg3,~,~] = expfn3(u, v);
[~,arg4,~] = expfn3(u, v);

You can use the `mineval`

output in a subsequent constraint expression.