Main Content

# Rational Objective Function, Problem-Based

The problem-based approach to optimization involves creating optimization variables and expressing the objective and constraints in terms of those variables.

A rational function is a quotient of polynomials. When the objective function is a rational function of optimization variables or other supported function, you can create the objective function expression directly from the variables. In contrast, when your objective function is not a supported function, you must create a MATLAB® function that represents the objective and then convert the function to an expression by using `fcn2optimexpr`. See Supported Operations on Optimization Variables and Expressions and Convert Nonlinear Function to Optimization Expression.

For example, write the objective function

`$f=\frac{\left(x-y{\right)}^{2}}{4+\left(x+y{\right)}^{4}}\frac{x+{y}^{2}}{1+{y}^{2}}$`

in terms of two optimization variables `x` and `y`.

```x = optimvar('x'); y = optimvar('y'); f = (x-y)^2/(4+(x+y)^4)*(x+y^2)/(1+y^2);```

To find the minimum of this objective function, create an optimization problem with `f` as the objective, set an initial point, and call `solve`.

```prob = optimproblem('Objective',f); x0.x = -1; x0.y = 1; [sol,fval,exitflag,output] = 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: -2.1423 y: 0.7937 ```
```fval = -1.0945 ```
```exitflag = OptimalSolution ```
```output = struct with fields: iterations: 9 funcCount: 10 stepsize: 1.7073e-06 lssteplength: 1 firstorderopt: 1.4999e-07 algorithm: 'quasi-newton' message: '...' objectivederivative: "reverse-AD" solver: 'fminunc' ```

The exit flag shows that the reported solution is a local minimum. The output structure shows that the solver took just 30 function evaluations to reach the minimum.

Download now