Creating an Example Embedded MATLAB Function

Adding an Embedded MATLAB Function Block to a Model

Start by creating an empty model and filling it with an Embedded MATLAB Function block, and other blocks necessary to complete the model.

  1. Create a new model with the Simulink product and add an Embedded MATLAB Function block to it from the User-Defined Function library.

    An Embedded MATLAB Function block has two names. The name in the middle of the block is the name of the function you build for the Embedded MATLAB Function block. Its name defaults to fcn. The name at the bottom of the block is the name of the block itself. Its name defaults to Embedded MATLAB Function.

    The default Embedded MATLAB Function block has an input port and an output port. The input port is associated with the input argument u, and the output port is associated with the output argument y.

  2. Add the following Source and Sink blocks to the model:

    The model should now have the following appearance:

  3. In the window displayed by the Simulink product, select File > Save As and save the model as call_stats_block1.

Programming the Embedded MATLAB Function

The following exercise shows you how to program the block to calculate the mean and standard deviation for a vector of values:

  1. Open the call_stats_block1 model that you saved at the end of Adding an Embedded MATLAB Function Block to a Model. Double-click the Embedded MATLAB Function block fcn to open it for editing.

    The Embedded MATLAB Editor appears.

    The Embedded MATLAB Editor window is titled with the syntax <model name>/<Embedded MATLAB Function block name> in its header. In this example, the model name is call_stats_block1, and the block name is Embedded MATLAB Function, the name that appears at the bottom of the Embedded MATLAB Function block.

    Inside the Embedded MATLAB Editor is an edit window for editing the function that specifies the Embedded MATLAB Function block. A function header with the function name fcn is at the top of the edit window. The header specifies an argument to the function, u, and a return value, y.

  2. Edit the function header line with the return values, function name, and argument:

    function [mean,stdev] = stats(vals)
    

    The Embedded MATLAB function stats calculates a statistical mean and standard deviation for the values in the vector vals. The function header declares vals to be an argument to the stats function and mean and stdev to be return values from the function.

  3. In the Embedded MATLAB Editor, select File > Save As and save the model as call_stats_block2.

    Saving the model updates the model window, which now looks like this:

    Changing the function header of the Embedded MATLAB Function block makes the following changes to the Embedded MATLAB Function block in the Simulink model:

  4. Complete the connections to the Embedded MATLAB Function block as shown.

  5. In the Embedded MATLAB Editor, enter a line space after the function header and replace the default comment line with the following comment lines:

    % calculates a statistical mean and a standard
    % deviation for the values in vals.
    

    You specify comments with a leading percent (%) character, just as you do in MATLAB.

  6. Enter a line space after the comments and replace the default function line y = u; with the following:

    len = length(vals);
    

    The function length is an example of a built-in function supported by the runtime function library for Embedded MATLAB Function blocks. This length works just like the MATLAB function length. It returns the vector length of its argument vals. However, when you simulate this model, C code is generated for this function in the simulation application. Callable functions supported for Embedded MATLAB Function blocks are listed in the topic Embedded MATLAB Function Library Reference in the Embedded MATLAB documentation.

    The variable len is a local variable that is automatically typed as a scalar double because the Embedded MATLAB runtime library function, length, returns a scalar of type double. If you want, you can declare len to have a different type and size by changing the way you declare it in the function. See in the Embedded MATLAB documentation for details about implicitly declaring local variables in an Embedded MATLAB Function block.

    By default, implicitly declared local variables like len are temporary. They come into existence only when the function is called and cease to exist when the function is exited. To persist implicitly declared variables between function calls, see Declaring Persistent Variables in the Embedded MATLAB documentation.

  7. Enter the following lines to calculate the value of mean and stdev:

    mean = avg(vals,len);
    stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
    

    stats stores the mean and standard deviation values for the values in vals in the variable mean and stdev, which are output by port to the Display blocks in the model. The line that calculates mean calls a subfunction, avg, that has not been defined yet. The line that calculates stdev calls the Embedded MATLAB runtime library functions sqrt and sum.

  8. Enter the following line to plot the input values in vals.

    plot(vals,'-+');
    

    This line calls the function plot to plot the input values sent to stats against their vector indices. Because the Embedded MATLAB runtime library has no plot function, you need to declare the plot function to be extrinsic. An extrinsic function is a function that is executed by MATLAB software during simulation.

  9. To declare the plot function to be extrinsic, add the declaration:

    eml.extrinsic('plot');
    

    after the comments at the top of the Embedded MATLAB function.

    See Calling MATLAB Functions in the Embedded MATLAB documentation for more details on using this mechanism to call MATLAB functions from Embedded MATLAB functions.

  10. At the bottom of the Embedded MATLAB function, enter a line space followed by the following lines for the subfunction avg, which is called in an earlier line.

    function mean = avg(array,size)
    mean = sum(array)/size;
    

    These two lines define the subfunction avg. You are free to use subfunctions in Embedded MATLAB function code with single or multiple return values, just as you do in regular MATLAB functions.

    The Embedded MATLAB Editor should now have the following appearance:

  11. Save the model as call_stats_block2.

Building the Function and Checking for Errors

After programming an Embedded MATLAB Function block in a Simulink model, you can build the function and test for errors. This section describes the steps:

  1. Set up your compiler.

  2. Build the function.

  3. Locate and fix errors.

Setting Up Your Compiler

Before building your Embedded MATLAB Function block, you must set up your C compiler by running the mex -setup command, as described in the documentation for mex in the MATLAB Function Reference. You must run this command even if you use the default C compiler that comes with the MATLAB product for Microsoft Windows platforms. You can also use mex to choose and configure a different C compiler, as described in Building MEX-Files in the MATLAB External Interfaces documentation.

Supported Compilers for Simulation Builds.   You can use the following compilers to build models containing Embedded MATLAB Function blocks for simulation:

Supported Compilers for Code Generation.   To generate code for models that contain Embedded MATLAB Function blocks, you can use any of the C compilers supported by Simulink software for code generation with Real-Time Workshop. For a list of these compilers:

  1. Navigate to theSupported and Compatible Compilers Web page.

  2. Select your platform.

  3. In the table for Simulink and related products, find the compilers checked in the column titled Real-Time Workshop.

How to Build the Embedded MATLAB Function

To build the function that calculates the mean and standard deviation:

How to Locate and Fix Errors

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

The following exercise shows how to locate and fix an error in an Embedded MATLAB Function block:

  1. In the stats function, change the subfunction avg to a fictitious subfunction aug and then compile to see the following messages in the Diagnostics Manager window:

    Each detected error appears with a red button.

  2. Click the first error line to display its diagnostic message in the bottom half of the error window.

  3. In the diagnostic message for the selected error, click the blue link to find the offending code:

    The offending line appears highlighted in the Embedded MATLAB Editor:

  4. Correct the error by changing aug back to avg and recompile. No errors are found and the compile completes successfully.

Defining Inputs and Outputs

In the stats function header for the Embedded MATLAB Function block you defined in Programming the Embedded MATLAB Function, the function argument vals is an input and mean and stdev are outputs. By default, function inputs and outputs inherit their data type and size from the signals attached to their ports. In this topic, you examine input and output data for the Embedded MATLAB Function block to verify that it inherits the correct type and size.

  1. Open the call_stats_block2 model that you saved at the end of Programming the Embedded MATLAB Function. Double-click the Embedded MATLAB Function block stats to open it for editing.

  2. In the Embedded MATLAB Editor, select Tools > Model Explorer.

    The Model Explorer window opens:

    You can use the Model Explorer to define arguments for Embedded MATLAB Function blocks. Notice that the Embedded MATLAB Function block Embedded MATLAB is highlighted in the left Model Hierarchy pane.

    The Contents pane displays the argument vals and the return values mean and stdev that you have already created for the Embedded MATLAB Function block. Notice 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.

    You can also use the Ports and Data Manager to define arguments for Embedded MATLAB Function blocks (see Ports and Data Manager).

  3. In the Contents pane of the Model Explorer window, click anywhere in the row for vals to highlight it:

    The right pane displays the Data properties dialog box for vals. By default, the type, size, 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 compilation of the model, and are reported in the Compiled Type and Compiled Size columns of the Contents pane.

    You can specify the type of an input or output argument by selecting a type 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 of the Data properties dialog box for the argument. For example, you can enter [2 3] in the Size field to size vals as a 2-by-3 matrix. See Typing Function Arguments and Sizing Function Arguments for more information on the expressions that you can enter for type and size.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS