# Documentation

## Write a Cost Function

### Cost Function Overview

When you use `sdo.optimize` to optimize model parameters (design variables), you must provide a MATLAB® function as an input to `sdo.optimize`. This function, also called a cost function, must evaluate the cost and constraint values for the design variable values for an iteration. (The cost and constraint functions are collectively referred to as requirements.) `sdo.optimize` calls this function at every optimization iteration and uses the function output to decide the optimization direction.

The cost function can also be used for global sensitivity analysis. You generate samples of the model parameters and evaluate the cost function for each sample using `sdo.evaluate`.

The cost function must have:

• Input — `params` , a vector of the design variables (`param.Continuous` objects) to be optimized.

• Output:

• (Required) `vals` , a structure with one or more fields that specify the values of the cost and constraint violations.

• (Optional) `derivs`, a structure with one or more fields that specify the values of the gradients of the cost and constraint violations.

You perform the following tasks within the cost function:

• Extract the current design variable values from `params`.

• If the simulated response is required for evaluating the requirements, simulate the model using the current design variable values.

• Evaluate the requirements.

• Specify the requirement values as fields of `vals`.

To use a cost function with `sdo.optimize`, enter:

`[param_opt,opt_info] = sdo.optimize(@myCostFunc,param)`

Here, `myCostFunc` is the name of the MATLAB function and `param` is a vector of the design variables.

Similarly, to use a cost function with `sdo.evaluate`, enter:

`[y,info] = sdo.evaluate(@myCostFunc,param)`

### Convenience Objects

The software provides you with the following convenience objects that can you can use in the cost function:

Class NameDescription
`sdo.SimulationTest`

Use an `sdo.SimulationTest` object, also referred to as a simulator, to simulate a model. The simulator allows you to simulate the model using alternative inputs, model parameter and initial-state values, without modifying the model.

You configure the simulator to log the signals needed to evaluate requirements and use the `sim` method to simulate the model. Then, you extract the model response from the object and evaluate the requirements.

Use these requirements objects to specify time- and frequency-domain costs or constraints on the design variables.

You configure the properties of the object and then use the object's `evalRequirement` method to evaluate how closely the current design variables satisfy your design requirement.

`sdo.Experiment`

Use an `sdo.Experiment` object, also referred to as simply an experiment, to specify the input/output data, model parameter and initial-state values for parameter estimation.

You update the design variable values associated with the experiment using the `setEstimatedValues` method. Then, you create a simulator, using the `createSimulator` method, to simulate the model using the updated model configuration.

### Inputs

#### Model Parameters and States

The function must take as input a vector of model parameter objects (`param.Continuous` objects) and, optionally, initial-state objects (`param.State` objects). These objects represent the design variables of the optimization problem. You obtain these objects by using the `sdo.getParameterFromModel` and `sdo.getStateFromModel` commands.

To access a design variable value, use:

`param_val = p(1).Value;`

Here, `p` is a vector of `param.Continuous` objects and `p(1)` is either a model parameter or an initial-state object.

#### Multiple Inputs

`sdo.optimize` requires that the cost function accept only one input argument, `params`. However, you might want your cost function to use additional inputs. For instance, you could make the model name an input argument and configure the function to be used for multiple models. To call `sdo.optimize` and use a function that accepts more than one input argument, you use an anonymous function. For example, suppose `myCostFunc_mult_inputs` is a cost function that takes `param`, `arg1`, and `arg2 ` as inputs. Then, assuming that all input arguments are variables in the workspace, you enter:

```myCostFunc = @(param) myCostFunc_mult_inputs(param,arg1,arg2); [param_opt,opt_info] = sdo.optimize(@myCostFunc,param);```

Additional inputs can also help reduce code redundancy and computation cost, given that the function is called repeatedly by `sdo.optimize` during optimization. If you use a convenience object in your function, you can create it once, before calling `sdo.optimize`. For example, you can create a simulator (`sdo.SimulationTest` object) to simulate your model, and pass it to your cost function.

```simulator = sdo.SimulationTest(model) myCostFunc = @(param) myCostFunc_mult_inputs(param,arg1,arg2,simulator); [param_opt,opt_info] = sdo.optimize(@myCostFunc,param);```
 Note:   To perform estimation, optimization, or evaluation using Simulink® fast restart at the command line , it is necessary to create the simulator before the cost function, and then pass the simulator to the cost function.

### Evaluate Requirements

The core of the cost function is where you evaluate how well the current design variables satisfy the design requirements. You can use MATLAB functions to do so. You can also use the requirements objects that the Simulink Design Optimization™ software provides. These objects enable you to specify requirements such as step-response characteristics, gain/phase margin bounds, Bode magnitude bounds, etc.

• Parameter-only requirements — Extract the design variable values and compute the requirement values.

For example, you can minimize the cylinder cross-sectional area, a design variable, in a hydraulic cylinder. See Design Optimization to Meet a Custom Objective (Code).

• Model signal-based requirements — Simulate the model using the current design variable values, extract the model response, and compute the requirement values.

There are multiple ways to simulate the model, including:

• Linear model-based requirements — Update the model with the current design variable values, linearize the model, and compute the requirement values.

Use `sdo.setValueInModel` to update the model. To linearize the model use functions such as `linmod`, `linearize` (requires a Simulink Control Design™), or the `SystemLoggingInfo` property of `sdo.SimulationTest`.

 Note:   In fast restart mode, you cannot use the `linearize` command. Use the `SystemLoggingInfo` property of the `sdo.SimulationTest` object, to specify linear systems to log when simulating the model. For an example, see Design Optimization to Meet Frequency-Domain Requirements (Code).

### Outputs

#### Cost and Constraint Values

Your cost function must return a structure containing the cost and constraint values for the current design variables. This structure must have one or more of the following fields, as required by your optimization problem:

• `F` — Cost value.

• `Cleq`, `Ceq` — Nonlinear constraint values. The solver satisfies `Cleq``0` and ```Ceq = 0```.

• `leq`, `eq` — Linear constraint values. The solver satisfies `leq``0` and ```eq = 0```.

If you have multiple constraints of one type, concatenate the values into a vector, and specify this vector as the corresponding field value. For instance, if you have a hydraulic cylinder, you can specify nonlinear inequality constraints on the piston position (`Cleq1`) and cylinder pressure (`Cleq2`). In this case, specify the `Cleq` field of the output structure, `vals`, as:

`vals.Cleq = [Cleq1; Cleq2];`

For an example, see Design Optimization to Meet a Custom Objective (Code).

By default, the software computes the cost and constraint gradients using numeric perturbation. However, you can specify the gradients and return them as an additional output. This output must be a structure with one or more of the following fields, as required by your optimization problem:

• `F` — Cost derivatives.

• `Cleq` — Nonlinear inequality constraints derivatives.

• `Ceq` — Nonlinear equality constraints derivatives.

You must also set the `GradFcn` property of the optimization option set to `'on'`.

#### Multiple Objectives

Simulink Design Optimization does not support multi-objective optimization. However, you can return the cost value (`F`) as a vector, representing the multiple objective values. Using this approach does not halt the optimization. Instead, the software sums the elements of the vector and minimizes this sum. The exception to this behavior is if you are using the nonlinear least squares (`lsqnonlin`) optimization method. The nonlinear least squares method, used for parameter estimation, requires that you return the error residuals as a vector. In this case, the software minimizes the sum square of this vector.

If you are tracking multiple signals and using `lsqnonlin`, then you must concatenate the error residuals for the different signals into one vector. Specify this vector as the `F` field value.

For an example of single objective optimization using the gradient descent method, see Design Optimization to Meet a Custom Objective (Code).

For an example of multiple objective optimization using the nonlinear least squares method, see Estimate Model Parameters Per Experiment (Code).

Get trial now