Documentation Center

  • Trial Software
  • Product Updates

Build Model with MATLAB Function in a Chart

This section explains how to create a model with a Stateflow® chart that calls two MATLAB® functions, meanstats and stdevstats. meanstats calculates a mean and stdevstats calculates a standard deviation for the values in vals and outputs them to the Stateflow data mean and stdev, respectively.

Follow these steps:

  1. Create a new model with the following blocks:

  2. Save the model as call_stats_function_stateflow.

  3. In the model, double-click the Chart block.

  4. Drag two MATLAB functions into the empty chart using this icon from the toolbar:

    A text field with a flashing cursor appears in the middle of each MATLAB function.

  5. Label each function as shown:

    You must label a MATLAB function with its signature. Use the following syntax:

    [return_val1, return_val2,...] = function_name(arg1, arg2,...)
    

    You can specify multiple return values and multiple input arguments, as shown in the syntax. Each return value and input argument can be a scalar, vector, or matrix of values.

      Note:   For MATLAB functions with only one return value, you can omit the brackets in the signature label.

  6. In the chart, draw a default transition into a terminating junction with this condition action:

    {
    mean = meanstats(invals);
    stdev = stdevstats(invals);
    }
    

    The chart should look something like this:

      Tip   If the formal arguments of a function signature are scalars, verify that inputs and outputs of function calls follow the rules of scalar expansion. For more information, see How Scalar Expansion Works for Functions.

  7. In the chart, double-click the function meanstats to edit its function body in the editor.

  8. In the function editor, select Tools > Model Explorer to open the Model Explorer.

    The function meanstats is highlighted in the Model Hierarchy pane. The Contents pane displays the input argument vals and output argument meanout. Both are scalars of type double by default.

  9. Double-click the vals row under the Size column to set the size of vals to 4.

  10. Back in the chart, double-click the function stdevstats and repeat the previous two steps.

  11. Back in the Model Hierarchy pane of the Model Explorer, select Chart and add the following data:

    Name

    Scope

    Size

    invals

    Input

    4

    mean

    Output

    Scalar (no change)

    stdev

    Output

    Scalar (no change)

    You should now see the following data in the Model Explorer.

    After you add the data invals, mean, and stdev to the chart, the corresponding input and output ports appear on the Stateflow block in the model.

  12. Connect the Constant and Display blocks to the ports of the Chart block and save the model.

To program the functions meanstats and stdevstats, see Program a MATLAB Function in a Chart.

Was this topic helpful?