Writing Level-2 M-File S-Functions

About Level-2 M-File S-Functions

The Level-2 M-file S-function API allows you to use the MATLAB M language to create custom blocks with multiple input and output ports and capable of handling any type of signal produced by a Simulink model, including matrix and frame signals of any data type. The Level-2 M-file S-function API corresponds closely to the API for creating C MEX-file S-functions. Much of the documentation for creating C MEX-file S-functions (see Writing S-Functions in C and Implementing Block Features) applies also to Level-2 M-file S-functions. To avoid duplication, this section focuses on providing information that is specific to writing Level-2 M-file S-functions.

A Level-2 M-file S-function is an M-file that defines the properties and behavior of an instance of a Level-2 M-File S-Function block that references the M-file in a Simulink model. The M-file itself comprises a set of callback methods (see Level-2 M-File S-Function Callback Methods) that the Simulink engine invokes when updating or simulating the model. The callback methods perform the actual work of initializing and computing the outputs of the block defined by the S-function.

To facilitate these tasks, the engine passes a run-time object to the callback methods as an argument. The run-time object effectively serves as an M proxy for the S-Function block, allowing the callback methods to set and access the block properties during simulation or model updating.

About Run-Time Objects

When the Simulink engine invokes a Level-2 M-file S-function callback method, it passes an instance of the Simulink.MSFcnRunTimeBlock class to the method as an argument. This instance, known as the run-time object for the S-Function block, serves the same purpose for Level-2 M-file S-function callback methods as the SimStruct structure serves for C MEX-file S-function callback methods. The object enables the method to provide and obtain information about various elements of the block ports, parameters, states, and work vectors. The method does this by getting or setting properties or invoking methods of the block run-time object. See the documentation for the Simulink.MSFcnRunTimeBlock class for information on getting and setting run-time object properties and invoking run-time object methods.

Run-time objects do not support MATLAB sparse matrices. For example, if the variable block is a run-time object, the following line in a Level-2 M-file S-function produces an error:

block.Outport(1).Data = speye(10);

where the speye command forms a sparse identity matrix.

Level-2 M-File S-Function Template

Use the basic Level-2 M-file S-function template

 matlabroot/toolbox/simulink/blocks/msfuntmpl_basic.m

to get a head start on creating a new Level-2 M-file S-function. The template contains skeleton implementation of the required callback methods defined by the Level-2 M-File S-function API. To write a more complicated S-function, use the annotated template

matlabroot/toolbox/simulink/blocks/msfuntmpl.m

To create an M-file S-function, make a copy of the template and edit the copy as necessary to reflect the desired behavior of the S-function you are creating. The following two sections describe the contents of the M-file template. The section Example of Writing a Level-2 M-File S-Function describes how to write a Level-2 M-file S-function that models a unit delay.

Level-2 M-File S-Function Callback Methods

The Level-2 M-file S-function API defines the signatures and general purposes of the callback methods that constitute a Level-2 M-file S-function. The S-function itself provides the implementations of these callback methods. The implementations in turn determine the block attributes (e.g., ports, parameters, and states) and behavior (e.g., the block outputs as a function of time and the block inputs, states, and parameters). By creating an S-function with an appropriate set of callback methods, you can define a block type that meets the specific requirements of your application.

A Level-2 M-file S-function must include the following callback methods:

Your S-function can contain other methods, depending on the requirements of the block that the S-function defines. The methods defined by the Level-2 M-file S-function API generally correspond to similarly named methods defined by the C MEX-file S-function API. For information on when these methods are called during simulation, see Process View in How the Simulink Engine Interacts with C S-Functions. For instructions on how to implement each callback method, see S-Function Callback Methods — Alphabetical List.

The following table lists all the Level-2 M-file S-function callback methods and their C MEX-file counterparts.

Level-2 M-File Method

Equivalent C MEX-File Method

setup (see Using the setup Method)

mdlInitializeSizes

CheckParameters

mdlCheckParameters

Derivatives

mdlDerivatives

Disable

mdlDisable

Enable

mdlEnable

InitializeCondition

mdlInitializeConditions

Outputs

mdlOutputs

PostPropagationSetup

mdlSetWorkWidths

ProcessParameters

mdlProcessParameters

Projection

mdlProjection

SetInputPortComplexSignal

mdlSetInputPortComplexSignal

SetInputPortDataType

mdlSetInputPortDataType

SetInputPortDimensions

mdlSetInputPortDimensionInfo

SetInputPortSampleTime

mdlSetInputPortSampleTime

SetInputPortSamplingMode

mdlSetInputPortFrameData

SetOutputPortComplexSignal

mdlSetOutputPortComplexSignal

SetOutputPortDataType

mdlSetOutputPortDataType

SetOutputPortDimensions

mdlSetOutputPortDimensionInfo

SetOutputPortSampleTime

mdlSetOutputPortSampleTime

SimStatusChange

mdlSimStatusChange

Start

mdlStart

Terminate

mdlTerminate

Update

mdlUpdate

WriteRTW

mdlRTW

Using the setup Method

The body of the setup method in a Level-2 M-file S-function initializes the instance of the corresponding Level-2 M-File S-Function block. In this respect, the setup method is similar to the mdlInitializeSizes and mdlInitializeSampleTimes callback methods implemented by C MEX S-functions. The setup method performs the following tasks:

Example of Writing a Level-2 M-File S-Function

The following steps illustrate how to write a simple Level-2 M-file S-function. When applicable, the steps include examples from the S-function demo matlabroot/toolbox/simulink/blocks/msfcn_unit_delay.m used in the model msfcndemo_sfundsc2.mdl. All lines of code use the variable name block for the S-function run-time object.

  1. Copy the Level-2 M-file S-function template msfuntmpl_basic.m to your working directory. If you change the file name when you copy the file, change the function name in the function line to the same name.

  2. Modify the setup method to initialize the S-function's attributes. For this example:

    The following setup method from msfcn_unit_delay.m performs the previous list of steps:

    function setup(block)
    
    %% Register a single dialog parameter
    block.NumDialogPrms  = 1;
    
    %% Register number of input and output ports
    block.NumInputPorts  = 1;
    block.NumOutputPorts = 1;
    
    %% Setup functional port properties to dynamically
    %% inherited.
    block.SetPreCompInpPortInfoToDynamic;
    block.SetPreCompOutPortInfoToDynamic;
    
    %% Hard-code certain port properties
    block.InputPort(1).Dimensions        = 1;
    block.InputPort(1).DirectFeedthrough = false;
    
    block.OutputPort(1).Dimensions       = 1;
    
    %% Set block sample time to inherited
    block.SampleTimes = [-1 0];
    
    %% Register methods
    block.RegBlockMethod('PostPropagationSetup',@DoPostPropSetup);
    block.RegBlockMethod('InitializeConditions',@InitConditions);
    block.RegBlockMethod('Outputs',             @Output);  
    block.RegBlockMethod('Update',              @Update);  

    If your S-function needs continuous states, initialize the number of continuous states in the setup method using the run-time object's NumContStates property. Do not initialize discrete states in the setup method.

  3. Initialize the discrete states in the PostPropagationSetup method. A Level-2 M-file S-function stores discrete state information in a DWork vector. The default PostPropagationSetup method in the template file suffices for this example.

    The following PostPropagationSetup method from msfcn_unit_delay.m, named DoPostPropSetup, initializes one DWork vector with the name x0.

    function DoPostPropSetup(block)
    
      %% Setup Dwork
      block.NumDworks = 1;
      block.Dwork(1).Name = 'x0'; 
      block.Dwork(1).Dimensions      = 1;
      block.Dwork(1).DatatypeID      = 0;
      block.Dwork(1).Complexity      = 'Real';
      block.Dwork(1).UsedAsDiscState = true;

    If your S-function uses additional DWork vectors, initialize them in the PostPropagationSetup method, as well (see Using DWork Vectors in Level-2 M-File S-Functions).

  4. Initialize the values of discrete and continuous states or other DWork vectors in the InitializeConditions or Start callback methods. Use the Start callback method for value that are initialized once at the beginning of the simulation. Use the InitializeConditions method for values that need to be reinitialized whenever an enabled subsystem containing the S-function is reenabled.

    For this example, use the InitializeConditions method to set the discrete state's initial condition to the value of the S-function's dialog parameter. For example, the InitializeConditions method in msfcn_unit_delay.m is:

    function InitConditions(block)
    
      %% Initialize Dwork
      block.Dwork(1).Data = block.DialogPrm(1).Data;

    For S-functions with continuous states, use the ContStates run-time object method to initialize the continuous state date. For example:

     block.ContStates.Data(1) = 1.0;
  5. Calculate the S-function's outputs in the Outputs callback method. For this example, set the output to the current value of the discrete state stored in the DWork vector.

    The Outputs method in msfcn_unit_delay.m is:

    function Output(block)
    
      block.OutputPort(1).Data = block.Dwork(1).Data;
    
  6. For an S-function with continuous states, calculate the state derivatives in the Derivatives callback method. Run-time objects store derivative data in their Derivatives property. For example, the following line sets the first state derivative equal to the value of the first input signal.

    block.Derivatives(1).Data = block.InputPort(1).Data;

    This example does not use continuous states and, therefore, does not implement the Derivatives callback method.

  7. Update any discrete states in the Update callback method. For this example, set the value of the discrete state to the current value of the first input signal.

    The Update method in msfcn_unit_delay.m is:

    function Update(block)
    
      block.Dwork(1).Data = block.InputPort(1).Data;
    
  8. Perform any cleanup, such as clearing variables or memory, in the Terminate method. Unlike C MEX S-functions, Level-2 M-file S-function are not required to have a Terminate method.

For information on additional callback methods, see Level-2 M-File S-Function Callback Methods. For a list of run-time object properties, see the reference page for Simulink.MSFcnRunTimeBlock and the parent class Simulink.RunTimeBlock.

Instantiating a Level-2 M-File S-Function

To use a Level-2 M-file S-function in a model, copy an instance of the Level-2 M-File S-Function block into the model. Open the Block Parameters dialog box for the block and enter the name of the M-file that implements your S-function into the M-file name field. If your S-function uses any additional parameters, enter the parameter values as a comma-separated list in the Block Parameters dialog box Parameters field.

Generating Code from a Level-2 M-File S-Function

Generating code for a model containing a Level-2 M-file S-function requires that you provide a corresponding Target Language Compiler (TLC) file. You do not need a TLC file to accelerate a model containing a Level-2 M-file S-function. The Simulink Accelerator software runs Level-2 M-file S-functions in interpreted mode. See Inlining M-File S-Functions in the Real-Time Workshop User's Guide for more information on writing TLC files for M-file S-functions.

M-File S-Function Demos

The Level-2 M-file S-function demos provide a set of self-documenting models that illustrate the use of Level-2 M-file S-functions. Enter sfundemos at the MATLAB command prompt to view the demos.

  


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