Skip to Main Content Skip to Search
Home |   Australia  Choose Country  |  Contact Us  |  Cart Store 
Create Account | Log In
Products & Services Industries Academia Support User Community Company

 

MATLAB Digest - September 2004

Incorporating M-Code into Simulink Models


by Fred Smith and Jason Ghidella

You can incorporate code written in the MATLAB Language (M-code) into Simulink models in a variety of ways. With Release 14, Simulink 6 added two new capabilities: Embedded MATLAB Functions and Level 2 M-file S-functions. This article describes and clarifies the different ways in which you can incorporate M-code into your Simulink models, with a focus on how you can use M-code to model dynamic systems for simulation and code generation.

Simulink provides several user-defined functions for incorporating M-code into your model:

  • Fcn—applies a specified C language style expression to its input
  • MATLAB Fcn—applies a specified MATLAB function or expression to the input
  • Level 1 M-file S-function—provides limited access to Simulink custom block features
  • Level 2 M-file S-function—provides access to the most commonly used custom block features and is the preferred choice for implementing M-file S-functions. Here, we discuss only Level 2 M-file S-function capabilities.
  • Embedded MATLAB Function—lets you compose a MATLAB language function in a Simulink model that generates embeddable code
  • Stateflow—can also call MATLAB functions and include Embedded MATLAB Functions within it

As Table 1 shows, each of these blocks provides differing levels of functionality, so each is appropriate for certain tasks and not others.

  Fcn MATLAB Fcn Embedded MATLAB Function Level 2 M-file S-functions Stateflow
Commonly used S-function methods N N N Y N
Full MATLAB Language N Y N1 Y N1
Multiple Inputs/Outputs N N Y Y Y
Fast Update Diagram Y Y N5 Y N5
Low Simulation Overhead Y N Y2 N Y2
Code Generation Y N Y3 N4 Y3,9
Forward/Backward Propagation N N Y7 Y6 Y7
Comprehensive Data Attributes N N Y8 Y8 Y8
Table 1. User-Defined Blocks for incorporating M-code in Simulink 6

Table annotations:
  1. Embedded MATLAB Functions and Stateflow charts can call any MATLAB function for simulation only.
  2. Simulation overhead is low if debug instrumentation is turned off and the block does not call out to MATLAB.
  3. True, provided the Embedded MATLAB functions use only the supported subset of the MATLAB language.
  4. If you write a TLC implementation of your S-function, you can generate code.
  5. Update diagram is fast if the block has not changed since the last update.
  6. M-file S-functions can participate in propagation provided you manually implement the propagation rules. In simple scenarios (such as blocks with multiple input ports and one output port) you can choose not to implement the propagation rules and simply use the default Simulink rules for such blocks.
  7. Stateflow/Embedded MATLAB Functions in Simulink libraries do not participate in propagation.
  8. See Data Attributes discussion below for details.
  9. True if Stateflow does not use the “ml.” notation.

In the discussion that follows, we explain each of the functional areas listed in Table 1, and then conclude with some sample implementations using the different blocks.

S-function Methods

Simulink blocks communicate with the Simulink engine through the S-function API, a set of methods that fully specify the behavior of a Simulink block.

The most important method is mdlOutput. This method determines the value of the outputs given the value of the inputs. All the blocks for incorporating M-code into your model allow you to override this method.

The other S-function methods, such as mdlUpdate and mdlDerivatives, are less commonly used. If you need to change the behavior of these methods, use M-file S-functions. M-file S-functions support the most commonly used S-function methods, but do not support others. For example, M-file S-functions must have a single sample time for the block (rather than one for each port), and are unable to register new fixed-point types.

MATLAB Language

The MATLAB language, M, is a rich programming language with many constructs. M-file S-functions and the MATLAB Fcn block rely on the MATLAB interpreter and therefore support the whole language.

The Embedded MATLAB Function block implements a rich subset of M. When you simulate the model or generate code for a target environment, a function in an Embedded MATLAB Function block generates efficient C code. MATLAB language features, such as cell arrays and structures, and many library functions, are not available. During simulation, the Embedded MATLAB Function block permits calling arbitrary M functions using the MATLAB interpreter; thus indirectly supporting the full MATLAB language. (Refer to the documentation for complete details.)

Stateflow charts can use the MATLAB language either by including Embedded MATLAB Functions or by calling MATLAB using the “ml.” notation. The latter uses the MATLAB interpreter and therefore supports the whole language.

The Fcn block implements a variant of C and supports only a one-line expression. (We include the Fcn block in this discussion because for many simple expressions M and C are similar.)

Multiple Inputs and Outputs

Simulink blocks can have multiple inputs and multiple outputs. However, the MATLAB Fcn block and the Fcn block support only a single input and a single output, and the Fcn block can output only a scalar. When you use these blocks, you can use a Mux block to combine the inputs and a Demux block to separate the outputs.

Level 2 M-file S-functions, Stateflow, and Embedded MATLAB Function blocks support multiple inputs and outputs. M-file S-functions provide an added capability—they can be written to automatically adapt to their context. For example, you can write an M-file S-function so that the number of inputs and outputs depends on a parameter much like the Sum block.

Update Diagram

Before every simulation and when the user requests it, Simulink performs an “update diagram” (Ctrl-D) to ready the diagram for simulation. Each block introduces some overhead to this process.

Stateflow and Embedded MATLAB Function blocks perform simulation through code generation, which means that they can take a significant amount of time to update. However, the code generation is incremental so that if the block and the signals connected to it have not changed, this overhead will not be incurred.

M-file S-functions, MATLAB Fcn blocks, and Fcn blocks do not incur greater update diagram cost than other blocks. M-file S-functions however, can override some methods executed at update-diagram time, and if these methods become complex, they could contribute significantly to the update-diagram time.

Simulation Overhead

There are a number of factors that determine simulation speed. For any specific situation, determining performance characteristics and performance requirements requires a detailed analysis beyond the scope of this discussion. However, for most use cases, all of these blocks will provide acceptable performance.

Should performance be a key concern, this section may help you decide how to proceed. To obtain a more accurate indication of the actual performance, you can build a prototype with characteristics similar to your anticipated application. Use the profiler from the Simulink Accelerator to measure actual performance.

The Fcn block has the least simulation overhead. It is tightly integrated with the Simulink engine and implements a rudimentary expression language that is efficiently interpreted. This language has some limitations, for example, this block can output only scalar values.

The remaining blocks require a more detailed analysis. To this end, we separate the total execution cost into the interface cost and the algorithm cost. The interface cost is the time it takes to move the data from Simulink into the block. The algorithm cost is the time needed to perform the algorithm that the block implements.

The MATLAB Fcn block has a higher interface cost than most Simulink blocks and the same algorithm cost as MATLAB. When block data (such as inputs and outputs) is accessed or returned from a MATLAB Fcn block, this data is packaged into MATLAB arrays. This packaging takes additional time and causes a temporary increase in memory during communication. If you are passing large amounts of data across this interface, for example, frames or arrays, this overhead could be substantial. Once the data has been converted, the algorithm is executed using the MATLAB interpreter. As a result, the algorithm cost is the same as MATLAB. Efficient MATLAB code can be competitive with C code if the MATLAB JIT is able to optimize it, or if the code spends most of its time in MATLAB’s highly optimized library functions.

The M-file S-function block incurs the same algorithm costs as the MATLAB Fcn block, but a slightly higher interface cost. Because M-file S-functions can handle multiple inputs and outputs, the packaging is more complicated than for the MATLAB Fcn block. In addition, Simulink calls MATLAB for each of the block methods you have implemented (whereas for the MATLAB Fcn block, it calls MATLAB only for the mdlOutput method).

The Embedded MATLAB Function block performs simulation through code generation and so it incurs the same interface cost as standard Simulink blocks. The algorithm cost of this block is harder to analyze vis-à-vis MATLAB because of the different way in which it is implemented. Although we have not done extensive performance testing, our experience shows that, on average, the Embedded MATLAB Function and the MATLAB JIT run at about the same speed. To further reduce the execution cost, you can disable debugging for all the Embedded MATLAB Function blocks in your model.

If the Embedded MATLAB Function block uses simulation-only capabilities to call out to the MATLAB interpreter, it incurs all the costs that M-file S-function and MATLAB Fcn blocks incur. Calling out to the MATLAB Interpreter from Embedded MATLAB produces a warning to prevent you from doing so unintentionally.

Stateflow blocks that include Embedded MATLAB Functions will perform like the Embedded MATLAB Function block. Calls from Stateflow using the “ml.” notation incur the interface costs associated with calling the MATLAB interpreter.

Code Generation

Real-Time Workshop lets you generate embeddable C code from your Simulink models. Stateflow Coder lets you generate embeddable C code from your Stateflow charts.

The MATLAB Fcn block cannot be used to generate code.

The M-file S-function block can generate code only if you re-implement your algorithm in TLC. In accelerated and external mode simulations, you can still choose to execute the block in interpretive mode by calling back to MATLAB without implementing the block algorithm in TLC.

The Fcn block, the Embedded MATLAB Function block, and Stateflow natively support code generation. However, if your Embedded MATLAB Function or Stateflow block calls out to the MATLAB interpreter, it will not build with Real-Time Workshop. There is one exception for Embedded MATLAB Functions: if Real-Time Workshop can determine that the results of the calls to MATLAB do not affect the block outputs, these calls will simply be omitted from the generated C code. This feature is intended to allow you to leave visualization code in place, even when generating embedded code.

Forward and Backward Propagation

Many Simulink blocks can be configured to automatically inherit their data attributes, such as type and size, via forward or backward propagation. This capability minimizes data entry and makes it easier to change the data types of signals as your model evolves. (All blocks also allow these attributes to be manually specified.)

Inputs and outputs to the Fcn block, the Embedded MATLAB Function block, and the Stateflow block can inherit their data attributes and will do so by default. Embedded MATLAB Function and Stateflow blocks inside a Simulink Library model cannot inherit their data attributes.

In Stateflow you can add constraints to specify the data attributes of one data in terms of other data items.

The M-file S-function block offers the most flexibity with respect to propagation, as you can implement your own arbitrary type propagation algorithm. For example, you can specify that all the inputs must be double if one of them is complex, and single otherwise. If you do not wish to implement your own algorithm, the block provides a default implementation.

The MATLAB Fcn block does not support automatic inheritance of types, sizes, or complexity.

Data Attributes

Simulink signals can have a wide range of data attributes, summarized in Table 2 along with the support provided by each of the five user-defined blocks.

  Fcn MATLAB Fcn Embedded MATLAB Function M-file S-functions Stateflow
Integer N N Ya Y Yc
Fixed-point N N N Y Y
Single Y N Y Y Y
Double Y Y Y Y Y
Complex N Y Y Y N
Frame Nb Nb Nb Y Nb
Bus N N N N N
2-D Matrix output N Y Y Y Y
Table 2. User-Defined Block Support for Simulink Signal Data Attributes

Table annotations:
  1. Support for the new integer capabilities in MATLAB 7 is not yet available. You can read and write from integer matrices, however, other operations on integers generally require a cast to either single or double.
  2. You can use the Frame Status Conversion block from the Signal Processing Blockset to convert frames to or from matrices.
  3. Stateflow supports integer math, however, Embedded MATLAB Functions in Stateflow have the same functionality as Embedded MATLAB Function blocks.

Examples

This section discusses the tradeoffs in two sample models implemented using the different blocks. You can download the models from MATLAB Central.

Example 1: Complex Matrix Algorithm

This model implements an Extended Kalman Filter in M. We have not used the Fcn block, as it is not suitable for an implementation of this complexity. You can generate code only for the Embedded MATLAB Function version of the model (we have not provided a TLC implementation for the M-file S-function version).

Example 2: Simple Expression

This model implements the mass-flow rate equation from the Simulink and Stateflow demo of a fault tolerant fuel system, fuelsys.mdl:

mass-flow rate equation

This simple equation does not take long to compute, so interface costs and other simulation overheads account for most of the execution time. You can generate code only for the Embedded MATLAB Function and Fcn versions. To open this demo, just type the model name, fulesys, at the MATLAB command prompt.

Contact sales
E-mail this page
Print this page
Subscribe to newsletters