## Write a Cost Function

A cost function is a MATLAB^{®} function that evaluates your
design requirements using design variable values. After writing and
saving the cost function, you can use it for estimation, optimization,
or sensitivity analysis at the command line.

When you optimize or estimate model parameters, you provide
the saved cost function as an input to `sdo.optimize`

.
At every optimization iteration, `sdo.optimize`

calls
this function and uses the function output to decide the optimization
direction. When you perform sensitivity analysis using `sdo.evaluate`

, you generate sample values
of the design variables and evaluate the cost function for each sample
value using `sdo.evaluate`

.

### Anatomy of a Cost Function

To understand the parts of a cost function, consider the following sample function
`myCostFunc`

. For a design variable *x*,
`myCostFunc`

evaluates the objective
*x*^{2} and the nonlinearity constraint
*x*^{2}-4*x*+1 <=
0.

function [vals,derivs] = myCostFunc(params) % Extract the current design variable values from the parameter object, params. x = params.Value; % Compute the requirements (objective and constraint violations) and % assign them to vals, the output of the cost function. vals.F = x.^2; vals.Cleq = x.^2-4*x+1; % Compute the cost and constraint derivatives. derivs.F = 2*x; derivs.Cleq = 2*x-4; end

This cost function performs the following tasks:

Specifies the inputs of the cost function.

A cost function must have as input,

`params`

, a vector of the design variables to be estimated, optimized, or used for sensitivity analysis. Design variables are model parameter objects (`param.Continuous`

objects) or model initial states (`param.State`

objects).Since the cost function is called repeatedly during estimation, optimization, or evaluation, you can specify additional inputs to the cost function to help reduce code redundancy and computation cost. For more information, see Specify Inputs of the Cost Function.

Computes the requirements.

Requirements can be objectives and constraints based on model parameters, model signals, or linearized models. In this sample cost function, the requirements are based on the design variable

*x*, a model parameter. The cost function first extracts the current values of the design variables and then computes the requirements.For information about computing requirements based on model parameters, model signals, or linearized models, see Compute Requirements.

Specifies the requirement values as outputs,

`vals`

and`derivs`

, of the cost function.A cost function must return

`vals`

, a structure with one or more fields that specify the values of the objective and constraint violations.The output can optionally include

`derivs`

, a structure with one or more fields that specify the values of the gradients of the objective and constraint violations. For more information, see Specify Outputs of the Cost Function.

After saving the cost function as a MATLAB file `myCostFunc.m`

,
to perform the optimization, use the cost function as an input to `sdo.optimize`

.

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

When performing sensitivity analysis, to compute the requirements
in the cost function for a range of design variable sample values `paramsamples`

,
use the cost function as an input to `sdo.evaluate`

.

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

### Specify Inputs of the Cost Function

The sample cost function `myCostFunc`

takes
one input, `params`

.

`function [vals,derivs] = myCostFunc(params)`

A cost function must have as input, `params`

,
a vector of the design variables to be estimated, optimized, or used
for sensitivity analysis. Design variables are model parameter objects
(`param.Continuous`

objects)
or model initial states (`param.State`

objects). You obtain `params`

by
using the `sdo.getParameterFromModel`

and `sdo.getStateFromModel`

commands.

#### Specify Multiple Inputs

Because the cost function is called repeatedly during estimation,
optimization, or evaluation, you can specify additional inputs to
the cost function to help reduce code redundancy and computation cost.
However, `sdo.optimize`

and `sdo.evaluate`

accept
a cost function with only one input argument. To use a cost function
that accepts more than one input argument, you use an anonymous function.
Suppose that the `myCostFunc_multi_inputs.m`

file
specifies a cost function that takes `params`

and `arg1`

as
inputs. For example, you can make the model name an input argument, `arg1`

,
and configure the cost function to be used for multiple models. Then,
assuming that all input arguments are variables in the workspace,
specify an anonymous function `myCostFunc2`

, and
use it as an input to `sdo.optimize`

or `sdo.evaluate`

.

myCostFunc2 = @(params) myCostFunc_multi_inputs(params,arg1); [param_opt,opt_info] = sdo.optimize(@myCostFunc2,params);

You can also specify additional inputs using convenience objects
provided by Simulink^{®}
Design Optimization™ software. You create convenience
objects once and pass them as an input to the cost function to reduce
code redundancy and computation cost.

For example, you can create a simulator (`sdo.SimulationTest`

object)
to simulate your model using alternative model parameters without
modifying the model, and pass the simulator to your cost function.

simulator = sdo.SimulationTest(model) myCostFunc2 = @(params) myCostFunc_multi_inputs(params,arg1,arg2,simulator); [param_opt,opt_info] = sdo.optimize(@myCostFunc2,params);

For more information about the available convenience objects, see Convenience Objects as Additional Inputs. For an example, see Design Optimization to Meet a Custom Objective (Code).

### Compute Requirements

The sample cost function `myCostFunc`

computes the requirements based on a
model parameter `x`

. In general, requirements can be objectives or
constraints based on model parameters, model signals, or linearized models. As seen
in `myCostFunc`

, you can use MATLAB functions to compute the requirements. You can also use the
requirements objects that Simulink
Design Optimization software provides. These objects enable you to specify requirements
such as step-response characteristics, gain and phase margin bounds, and Bode
magnitude bounds. You can use the `evalRequirement`

method of these objects to evaluate the objective
and constraint violations. For a list of available requirement objects, see Convenience Objects as Additional Inputs.

#### Parameter-Based Requirements

If you have requirements on model parameters, in the cost function you first extract the current parameter values, and then compute the requirements.

Extract the current parameter value from

`params`

.x = params.Value;

Compute the requirement, and specify it as

`vals`

, the output of the cost function.Suppose that the objective to be computed is

*x*^{2}and the constraint is the nonlinearity constraint*x*^{2}-4*x*+1.vals.F = x.^2; vals.Cleq = x.^2-4*x+1;

In the context of optimization,

*x*^{2}is minimized subject to satisfying the constraints. For sensitivity analysis, the cost and constraints are evaluated for all values of the parameter`params`

.For more information about the output of a cost function, see Specify Outputs of the Cost Function.

For an example of a cost function with a parameter-based requirement, see Design Optimization to Meet a Custom Objective (Code). In this example, you minimize the cylinder cross-sectional area, a design variable in a hydraulic cylinder.

#### Model Signal Requirements

If you have requirements on model signals, in the cost function you simulate the model using current design variable values, extract the signal of interest, and compute the requirement on the signal.

Simulate the model using the current design variable values in

`param`

. There are multiple ways to simulate your model:**Using**— If an`sdo.SimulationTest`

object`sdo.SimulationTest`

object,`simulator`

, is a cost function input, you update the model parameter values using the`Parameters`

property of the simulator. Then use`sim`

to simulate the model.simulator.Parameters = params; simulator = sim(simulator);

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

**Using**— If you are performing parameter estimation based on input-output data defined in an`sdo.Experiment`

object`sdo.Experiment`

object,`exp`

, update the design variable values associated with the experiment using the`setEstimatedValues`

method. Create a simulator using the`createSimulator`

method, and simulate the model using the updated model configuration.exp = setEstimatedValues(exp,params); simulator = createSimulator(exp,simulator); simulator = sim(simulator);

For an example, see Estimate Model Parameters Per Experiment (Code).

**Using**— If you are not using`sim`

command`sdo.SimulationTest`

or`sdo.Experiment`

objects, use`sdo.setValueInModel`

to update the model parameter values, and then call`sim`

to simulate the model.sdo.setValueInModel('model_name',param); LoggedData = sim('model_name');

Extract the logged signal of interest,

`SignalOfInterest`

.Use the

`SignalLoggingName`

model parameter to get the simulation log name.logName = get_param(simulator.ModelName,'SignalLoggingName'); simLog = get(simulator.LoggedData,logName); Sig = get(simLog,'SignalOfInterest')

Evaluate the requirement, and specify it as the output of the cost function.

For example, if you specified a step-response bound on a signal using a

`sdo.requirements.StepResponseEnvelope`

object,`StepResp`

, you can use the`evalRequirement`

method of the object to evaluate the objective and constraint violations.vals.Cleq = evalRequirement(StepResp,SignalOfInterest.Values);

For an example, see Design Optimization to Meet Step Response Requirements (Code). For more information about the output of a cost function, see Specify Outputs of the Cost Function.

#### Linearization-Based Requirements

If you are optimizing or evaluating frequency-domain requirements, in the cost function you linearize the model, and compute the requirement values. Linearizing the model requires Simulink Control Design™ software.

Use the `SystemLoggingInfo`

property of `sdo.SimulationTest`

to
specify linear systems to log when simulating the model. For an example,
see Design Optimization to Meet Frequency-Domain Requirements (Code).
Alternatively, use `linearize`

(Simulink Control Design) to
linearize the model.

**Note**

For models in Simulink fast restart mode,
you cannot use the `linearize`

command.

### Specify Outputs of the Cost Function

The sample cost function `myCostFunc`

outputs `vals`

,
a structure with fields that specify the values of the objective and
constraint violations. The second output is `derivs`

,
a structure with fields that specify the derivatives of the objective
and constraint.

`function [vals,derivs] = myCostFunc(params)`

A cost function must output `vals`

, a structure
with one or more of the following fields that specify the values of
the objective and constraint violations:

`F`

— Value of the cost or objective evaluated at`param`

.`Cleq`

— Value of the nonlinear inequality constraint violations evaluated at`param`

. For optimization, the solver ensures`Cleq`

≤`0`

.`Ceq`

— Value of the nonlinear equality constraint violations evaluated at`param`

. For optimization, the solver ensures`Ceq = 0`

.`leq`

— Value of the linear inequality constraint violations evaluated at`param`

. For optimization, the solver ensures`leq`

≤`0`

.`eq`

— Value of the linear equality constraint violations evaluated at`param`

. For optimization, the solver ensures`eq = 0`

.`Log`

— Additional optional information from evaluation.

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 `sdo.optimize`

command computes
the objective and constraint gradients using numeric perturbation.
You can also optionally return the gradients as an additional cost
function output, `derivs`

. Where `derivs`

must
contain the derivatives of all applicable objective and constraint
violations and is specified as a structure with one or more of the
following fields:

`F`

— Derivatives of the cost or objective.`Cleq`

— Derivatives of the nonlinear inequality constraints.`Ceq`

— Derivatives of the nonlinear equality constraints.

The derivatives are not required for sensitivity analysis. For
estimation or optimization, specify the `GradFcn`

property
of `sdo.OptimizeOptions`

as `'on'`

.

#### Multiple Objectives

Simulink
Design Optimization software does not support multi-objective
optimization. However, you can return the objective value (`vals.F`

)
as a vector that represents the multiple objective values. The software
sums the elements of the vector and minimizes this sum. The exception
to this behavior is in the use of 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 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).

### Convenience Objects as Additional Inputs

A cost function must have as input, `params`

,
a vector of the design variables to be estimated, optimized, or used
for sensitivity analysis. You can specify additional inputs to the
cost function using convenience objects provided by the Simulink
Design Optimization software.
You create convenience objects once and pass them as an input to the
cost function to reduce code redundancy and computation cost. For
information about specifying additional inputs to the cost function,
see Specify Multiple Inputs.

Convenience Object | Class Name | Description |
---|---|---|

Simulator objects | `sdo.SimulationTest` | Use the simulator object to simulate the model using
alternative inputs, model parameters, and initial-state values without
modifying the model. Use the In
the cost function, use the For an example, see Design Optimization to Meet a Custom Objective (Code).
To perform estimation, optimization, or evaluation using Simulink fast restart, it is necessary to create the simulator before the cost function, and then pass the simulator to the cost function. |

Requirements objects | Use these objects to specify time-domain and frequency-domain costs or constraints that depend on the design variable values. In the cost
function, use the For an example, see Design Optimization to Meet Step Response Requirements (Code). | |

Experiment objects | `sdo.Experiment` | Use an experiment object to specify the input-output data, model parameters, and initial-state values for parameter estimation. In
the cost function, update the design variable values associated with
the experiment using the For an example, see Estimate Model Parameters Per Experiment (Code). |

## See Also

`sdo.optimize`

| `sdo.OptimizeOptions`

| `sdo.evaluate`

| `sdo.setValueInModel`

| `param.Continuous`

| `sdo.SimulationTest`

| `sdo.Experiment`

## Related Topics

- How the Optimization Algorithm Formulates Minimization Problems
- Design Optimization to Meet a Custom Objective (Code)
- How the Software Formulates Parameter Estimation as an Optimization Problem
- Estimate Model Parameter Values (Code)
- What is Sensitivity Analysis?
- Identify Key Parameters for Estimation (Code)