Main Content

This example shows how to customize a model that uses the MATLAB Function block to calculate the mean and standard deviation for a vector of values.

The model `call_stats_block1`

includes an empty MATLAB Function block and the blocks you need for the example. Open the model to start.

Program the block to calculate the mean and standard deviation for a vector of values:

To open the

**MATLAB Function Block Editor**, double-click the MATLAB Function block. A default function appears in the**MATLAB Function Block Editor**with one input and output argument.Define the function inputs and outputs by editing the function declaration statement:

`function [mean, stdev] = stats(vals)`

From this code, you define a function called

`stats`

, which calculates a statistical mean and standard deviation for the values in the vector`vals`

. The function declaration statement declares`vals`

as an argument to the`stats`

function, with`mean`

and`stdev`

as return values.In the

**MATLAB Function Block Editor**, enter a line space after the function declaration statement and add the following code:% Calculates a statistical mean and a standard % deviation for the values in vals. len = length(vals); mean = avg(vals,len); stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len); plot(vals,'-+'); function mean = avg(array,size) mean = sum(array)/size;

Exit the block. The function outputs

`mean`

and`stdev`

correspond to block outports**mean**and**stdev**and the function input`vals`

corresponds to the block inport**vals**.Complete the connections to the MATLAB Function block as shown.

Save the model as

`call_stats_block2`

.

After programming the block in a Simulink^{®} model, you can build the function and test for errors. Building your
MATLAB Function block requires a supported compiler. MATLAB^{®} automatically selects one as the default compiler. If you have multiple
MATLAB-supported compilers installed on your system, you can change the default
compiler using the `mex -setup`

command. See Change Default Compiler.

View a list of compilers for building models containing MATLAB Function blocks simulation and code generation.

Navigate to the Supported and Compatible Compilers page and select your platform.

Scroll to the table under Simulink Product Family.

To check the table for models that contain MATLAB Function blocks for simulation, find the compilers checked in the column titled

`Simulink For Model Referencing, Accelerator mode, Rapid Accelerator mode, and MATLAB Function blocks`

.To check the table for models that contain MATLAB Function blocks and generate code, find the compilers checked in the column titled

`Simulink Coder™`

.

To generate code for models that contain MATLAB Function blocks, you can use any of the C compilers supported by Simulink software for code generation with Simulink Coder. For a list of these compilers:

Navigate to the Supported and Compatible Compilers Web page.

Select your platform.

In the table for Simulink and related products, find the compilers checked in the column titled Simulink Coder.

If errors occur during the build process, the **Diagnostics
Viewer** window lists the errors with links to the offending code.

The following exercise shows the way to locate and fix an error in a MATLAB Function block.

In the

`stats`

function, change the local function`avg`

to a fictitious local function`aug`

and then compile again to see the following messages in window. The**Diagnostics Viewer**window displays each detected error with a shaded red line.Investigate the error titled

`Undefined function or variable 'aug'`

. In the diagnostic message for the selected error, click the blue link after the function name to display the offending code. The offending line appears highlighted in the**MATLAB Function Block Editor**.The message also links to a report about compile-time type information for variables and expressions in your MATLAB functions. This information helps you diagnose error messages and understand type propagation rules. For more information about the report, see MATLAB Function Reports. To see the report, click the highlighted blue link in the line called

`Launch diagnostic report`

.Correct the error by changing

`aug`

back to`avg`

and recompile.

Each function argument in MATLAB Function blocks can have a unique data type that is a scalar, vector, or matrix. However, creating the function arguments does not directly specify their data type. By default, function inputs and outputs inherit their data type and size from the signals attached to their ports. Examine input and output data for the MATLAB Function block to verify that it inherits the correct type and size.

Double-click the MATLAB Function block

`stats`

.In the

**MATLAB Function Block Editor**, click**Ports & Data Manager**. The Ports and Data Manager opens to help you define arguments for MATLAB Function blocks.The left pane displays the argument

`vals`

and the return values`mean`

and`stdev`

that you have already created for the MATLAB Function block. Observe that`vals`

is assigned a**Scope**of`Input`

, which is short for**Input from Simulink**.`mean`

and`stdev`

are assigned the**Scope**of`Output`

, which is short for**Output to Simulink**.In the left pane of the Ports and Data Manager, click anywhere in the row for

`vals`

to highlight it.The right pane displays the

**Data**properties dialog box for`vals`

. By default, the class, size, units, and complexity of input and output arguments are inherited from the signals attached to each input or output port. Inheritance is specified by setting**Size**to`-1`

**, Complexity**to`Inherited`

, and**Type**to`Inherit: Same as Simulink`

.The actual inherited values for size and type are set during model compilation, and are reported in the

**Compiled Type**and**Compiled Size**columns of the left pane.You can specify the type of input or output argument in the

**Type**field of the**Data**properties dialog box, for example,`double`

. You can also specify the size of an input or output argument by entering an expression in the**Size**field. For example, you can enter`[2 3]`

in the**Size**field to specify`vals`

as a`2-by-3`

matrix. For more information, see Define and Modify Function Argument Types and Specify Size of MATLAB Function Block Data.**Note**The default first index for any arrays that you add to a MATLAB Function block function is

`1`

, just as it would be in MATLAB.

There are two programmatic approaches for configuring a MATLAB Function block:

Use a

`MATLABFunctionConfiguration`

object to query and modify the properties of the block. You can identify the block in your model by using a block path or calling the`gcb`

function.Use a

`Stateflow.EMChart`

object to access the inputs, outputs, and properties of the block. Identify the block in your model by navigating the hierarchy of Stateflow^{®}API objects.

Consider the model `call_stats_block1`

described in the previous
example. You can access the `MATLABFunctionConfiguration`

object for the
MATLAB Function block in this model by calling the `get_param`

function:

config = get_param('call_stats_block1/MATLAB Function', ... 'MATLABFunctionConfiguration');

To query or modify the properties in your configuration object, use dot notation with your object name:

myConfig.UpdateMethod

ans = 'Inherited'

`config.Description = 'Calculate the mean and standard deviation for a vector of values.';`

To learn more about the properties you can modify in your MATLAB
Function configuration object, see `MATLABFunctionConfiguration`

.

For greater programmatic control of your MATLAB Function block, access
its `Stateflow.EMChart`

object by calling the `find`

(Stateflow) function for the `Simulink.Root`

object at the top level
of the Stateflow hierarchy of objects.

rt = sfroot; block = find(rt,'-isa','Stateflow.EMChart', ... 'Path','call_stats_block1/MATLAB Function');

To query or modify the properties in your configuration object, use dot notation with your object name:

block.ChartUpdate

ans = 'INHERITED'

`block.Description = 'Calculate the mean and standard deviation for a vector of values.';`

The `Stateflow.EMChart`

object gives you access to additional
properties that are not available in the `MATLABFunctionConfiguration`

object. For example, to create a `table`

of the inputs and outputs of the block, enter:

info = get([block.Inputs;block.Outputs],{'Name','Scope','Port'}); T = table(info(:,2),cell2mat(info(:,3)), ... 'VariableNames',{'Scope','Port'}, ... 'RowNames',info(:,1)); T.Scope = categorical(T.Scope)

T = 3×2 table Scope Port ______ ____ vals Input 1 mean Output 1 stdev Output 2

For more information, see Overview of the Stateflow API (Stateflow).

To generate code from the MATLAB algorithm in a MATLAB Function block, you must explicitly
assign the class, size, and complexity of local variables before using them in operations or
returning them as outputs (see Data Definition for Code Generation). In the
example function `stats`

, the local variable `len`

is
defined before being used to calculate mean and standard deviation:

len = length(vals);

Once you assign properties to a variable, you cannot redefine its class, size, or complexity elsewhere in the function body with some exceptions (see Reassignment of Variable Properties).

Open the

`call_stats_block2`

model that you saved at the end of Program the MATLAB Function Block.Double-click

`stats`

block.Open the Simulink Coder app.

On the

**C Code**tab,**Build**to compile and build the example model.If you get an error related to the

`Variable-step`

solver, from**Configuration Parameters**>**Solver**, change the solver type to a`Fixed-step`

solver and rerun the build. To learn more about the differences between fixed-step and variable-step solvers, see Fixed-Step Versus Variable-Step Solvers.If no errors occur, the

**Diagnostics Viewer**window displays a message indicating success. Otherwise, this window helps you locate errors, as described in Locate and Fix Errors.

MATLAB Function | `add_block`

| `gcb`

| `get_param`

| `table`

| `MATLABFunctionConfiguration`

| `Stateflow.EMChart`

| MATLAB Function Block Editor