This example shows how to create a model that uses the MATLAB Function block to calculate the mean and standard deviation for a vector of values.
Create a new Simulink® model and insert a MATLAB Function block from the User-Defined Functions library.
Add a Constant block and set its value to vector
[2 3 4 5]. Add two Display blocks to the model.
Connect these blocks as shown in the diagram.
Save the model as
Program the block to calculate the mean and standard deviation for a vector of values:
Double-click the MATLAB Function block. A default function signature appears in the MATLAB Function Block Editor. Write any code inside the defined function signatures.
Edit the function header line:
function [mean,stdev] = stats(vals)
From this code, you define a function called
calculates a statistical mean and standard deviation for the values in the vector
vals. The function header declares
vals as an
argument to the
stats function, with
stdev as return values.
In the MATLAB Function Block Editor, enter a line space after the function header 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;
Save the model as
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 (MATLAB).
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
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.
stats function, change the local function
avg to a fictitious local function
then compile again to see the following messages in window. The Diagnostics Viewer window displays each detected error with a shaded red
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.
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
In the MATLAB Function Block Editor, select Edit
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
stdev that you have already created for
the MATLAB Function block. Observe that
assigned a Scope of
Input, which is
short for Input from Simulink.
stdev are assigned the Scope of
Output, which is short for Output to
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
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
-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. See Type Function Arguments and Size Function Arguments for more information on the
expressions that you can enter for type and size.
The default first index for any arrays that you add to a MATLAB
Function block function is
1, just as it would be in
You can create an object for the MATLAB Function block in your model, and
modify the properties that belong to this model. To query the properties in
call_stats_block2 model you just created, create a configuration
myconfig = get_param('call_stats_block2/MATLAB Function', 'MATLABFunctionConfiguration')
myconfig = MATLABFunctionConfiguration with properties: Path: 'call_stats_block2/MATLAB Function' FunctionScript: 'function [mean,stdev] = stats(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;↵' UpdateMethod: Inherited SampleTime: '-1' Description: '' DocumentLink: '' SupportVariableSizing: 1 AllowDirectFeedthrough: 1 SaturateOnIntegerOverflow: 1 TreatAsFi: FixedPoint FimathMode: SameAsMATLAB Fimath: 'fimath('RoundingMethod','Nearest','OverflowAction','Saturate','ProductMode','FullPrecision','SumMode','FillPrecision')'
myconfig.Description = 'This model outputs the mean and standard deviation values of an array'
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
stats, the local variable
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).
call_stats_block2 model that you saved at the end of
Program the MATLAB Function Block.
Select Build Model > Build to compile and build the example model.
If you get an error related to the
from Configuration Parameters > Solver, change the solver type to a
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.
This example shows how to programmatically add a MATLAB Function block to a model and populate the block with MATLAB code. If you already have MATLAB code and do not want to add it to a MATLAB Function block manually, this workflow can be convenient.
Create and save a model called
Create a MATLAB function with the following code and save it in
function c = myAdd(a, b) c = a + b;
Write a MATLAB script that adds a MATLAB Function block to
myModel and populates it with the contents of
% Add a MATLAB Function block to a model and populate the block with MATLAB % code. % % Copyright 2018 The Mathworks, Inc. open_system('myModel.slx'); libraryBlockPath = 'simulink/User-Defined Functions/MATLAB Function'; newBlockPath = 'myModel/myBlockName'; % Add a MATLAB Function to the model add_block(libraryBlockPath, newBlockPath); % In memory, open models and their parts are represented by a hierarchy of % objects. The root object is slroot. This line of the script returns the % object that represents the new MATLAB Function block: blockHandle = find(slroot, '-isa', 'Stateflow.EMChart', 'Path', newBlockPath); % The Script property of the object contains the contents of the block, % represented as a character vector. This line of the script loads the % contents of the file myAdd.m into the Script property: blockHandle.Script = fileread('myAdd.m'); % Alternatively, you can specify the code directly in a character vector. % For example: % blockHandle.Script = 'function c = fcn (a, b)';
Run the script and observe the new MATLAB Function block in
To see the code that you added to the block, double-click the