Level-2 MATLAB S-Functions
Level-2 MATLAB S-Functions
Contenido
General description ......................................................................................................................... 3 Working with Data Objects ............................................................................................................. 4 About Data Object Classes .......................................................................................................... 4 About Data Object Methods ....................................................................................................... 5 About Object Properties.............................................................................................................. 6 Handle Versus Value Classes ....................................................................................................... 6 Saving and Loading Data Objects ................................................................................................ 7 Using Data Objects in Simulink Models....................................................................................... 7 Creating Persistent Data Objects ................................................................................................ 7 Associating User Data with Blocks .............................................................................................. 8 Accessing Block Data During Simulation ......................................................................................... 8 About Block Run-Time Objects.................................................................................................... 8 Accessing a Run-Time Object .................................................................................................... 10 Listening for Method Execution Events .................................................................................... 10 Synchronizing Run-Time Objects and Simulink Execution ........................................................ 11 How the Simulink Engine Interacts with C MEX S-Functions ........................................................ 11 Process View ............................................................................................................................. 11 Data View .................................................................................................................................. 14 Writing Level-2 MATLAB S-Functions ............................................................................................ 14 Example of Writing a Level-2 MATLAB S-Function .................................................................... 15 Operations for Variable-Size Signals ......................................................................................... 17 Available S-Function Implementations ......................................................................................... 18 What Type of S-Function Should You Use? ............................................................................... 18 References..................................................................................................................................... 21
General description
You can create custom Simulink blocks whose properties and behaviors are defined by MATLAB functions called MATLAB S-functions. A Level-2 MATLAB S-function is a MATLAB function that defines the properties and behavior of an instance of a Level-2 MATLAB S-Function Simulink block that references the MATLAB function in a Simulink model.
Figura 1: An instance of a Level-2 MATLAB S-Function Simulink block references a MATLAB function in a Simulink model A MATLAB S-function must provide information about the function to the Simulink engine during the simulation. As the simulation proceeds, the engine, the ODE solver, and the MATLAB S-function interact to perform specific tasks. These tasks include defining initial conditions and block characteristics, and computing derivatives, discrete states, and outputs. S-functions use a special calling syntax called the Sfunction API that enables to interact with the Simulink engine. This interaction is very similar to the interaction that takes place between the engine and built-in Simulink blocks. The Level-2 MATLAB Sfunction API allows you to use the MATLAB language to create custom Simulink blocks with multiple input and output ports and capable of handling any type of signal produced by a Simulink model, including: Multiple input and output ports 1-D, 2-D, and n-D input and output signals All data types supported by the Simulink software Real or complex signals Frame-based signals Multiple sample rates User-defined data and work vectors Tunable and run-time parameters
The Simulink engine interacts with a MATLAB S-function by invoking callback methods that the S-function implements. Each method performs a predefined task, such as computing block outputs, required to simulate the block whose functionality the S-function defines. However, the S-function is free to perform the task in each method according to the functionality the S-function implements. For example, the mdlOutputs method must compute the block outputs at the current simulation time. However, the S-function can calculate these outputs in any way that is appropriate for the function. This callback-based API allows you to create Sfunctions, and hence custom blocks, of any desired functionality. If your block does not implement a particular feature, such as matrix signals, you are free to omit the callback methods needed to implement a feature. The callback methods 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 the application. A Level-2 MATLAB S-function must include (at least) the following callback methods: A setup function to initialize the basic S-function characteristics An Outputs function to calculate the S-function outputs
The body of the setup method in a Level-2 MATLAB S-function initializes the instance of the corresponding Level-2 MATLAB S-Function Simulink block. The setup method performs the following tasks: Initializing the number of input and output ports of the block. Setting attributes such as dimensions, data types, complexity, and sample times for these ports. Specifying the block sample time. Setting the number of S-function dialog parameters. Registering S-function callback methods by passing the handles of local functions in the MATLAB Sfunction to the RegBlockMethod method of the S-Function blocks run-time object. (See below about runtime objects)
The Simulink engine invokes the Outputs method at each simulation time step (or sample time step in the case of a discrete S-function) to compute the S-function output. The Outputs method computes the output of the block as a function of its inputs and, optionally, its states and parameters 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 a MATLAB proxy for the S-Function block, allowing the callback methods to set and access the block properties during simulation or model updating. When to Use an S-Function You can use Level-2 MATLAB S-functions for a variety of applications, including: Creating new general purpose blocks Describing a system as a set of mathematical equations Using graphical animations (see the inverted pendulum demo, penddemo)
based on Simulink reside in packages provided by those products. You can create your own packages for storing the classes that you define. You can also create subclasses of some of these built-in classes to specify attributes specific to your applications. Data objects specify values, data types, tunability, value ranges, and other key attributes of block outputs and parameters. You can create various types of data objects and assign them to workspace variables. You can use the variables in Simulink dialog boxes to specify parameter and signal attributes. This allows you to make model-wide changes to parameter and signal specifications simply by changing the values of a few variables. With Simulink objects you can parameterize the specification of a models data attributes. For information on working with specific kinds of data objects, see Simulink Classes. Class Naming Convention Simulink uses dot notation to name classes: PACKAGE.CLASS where CLASS is the name of the class and PACKAGE is the name of the package to which the class belongs, for example, Simulink.RunTimeBlock. This notation allows you to create and reference identically named classes that belong to different packages. In this notation, the name of the package is said to qualify the name of the class.
A class may define a set of methods having the same name as a method defined by one of its super classes. In this case, the method defined by the subclass takes priority over the behavior of the method defined by the parent class. The Simulink software determines which method to invoke at runtime from the class of the object that you specify as its first or implicit argument. Hence, the term dynamic method. Note Most Simulink data object methods are dynamic methods. Unless the documentation for a method specifies otherwise, you can assume that a method is a dynamic method. Static Methods A static method is a method whose identity depends only on its name and hence cannot change at runtime. To invoke a static method, use its fully qualified name, which includes the name of the class that defines it followed by the name of the method itself.
For example, Simulink.ModelAdvisor class defines a static method named getModelAdvisor. The fully qualified name of this static method is Simulink.ModelAdvisor.getModelAdvisor. The following example illustrates invocation of a static method.
ma = Simulink.ModelAdvisor.getModelAdvisor('vdp');
Constructors Every data class defines a method for creating instances of that class. The name of the method is the same as the name of the class. For example, the name of the Simulink.Parameter classs constructor is Simulink.Parameter. The constructors defined by Simulink data classes take no arguments. The value returned by a constructor depends on whether its class is a handle class or a value class. The constructor for a handle class returns a handle to the instance that it creates if the class of the instance is a handle class; otherwise, it returns the instance itself.
creates two instances of class Simulink.NumericType in the workspace, one assigned to the variable x and the other to y. About Handle Classes The constructor for a handle class returns a handle object. The handle can be assigned to multiple variables or passed to functions without causing a copy of the original object to be created. For example, Simulink.Parameter class is a handle class. Executing
>> x = Simulink.Parameter; >> y = x;
creates only one instance of Simulink.Parameter class in the MATLAB workspace. Variables x and y both refer to the instance via its handle. A program can modify an instance of a handle class by modifying any variable that references it, e.g., continuing the previous example,
>> x.Description = 'input gain'; >> y.Description ans = input gain
Most Simulink data object classes are value classes. Exceptions include Simulink.Signal and Simulink.Parameter class. You can determine whether a variable is assigned to an instance of a class or to a handle to that class by evaluating it at the MATLAB command line. MATLAB appends the text (handle) to the name of the object class in the value display, e.g.,
>> gain = Simulink.Parameter gain = Simulink.Parameter (handle) Value: [] RTWInfo: [1x1 Simulink.ParamRTWInfo] Description: '' DataType: 'auto' Min: -Inf Max: Inf DocUnits: '' Complexity: 'real' Dimensions: [0 0]
at the MATLAB command line sets load data_objects as the models preload function. This in turn causes the data objects to be loaded into the model workspace whenever you open the model.
The value of mydata can be any MATLAB data type, including arrays, structures, objects, and Simulink data objects. Use get_param to retrieve the user data associated with a block.
get_param(gcb, 'UserData')
The following command saves the user data associated with a block in the model file of the model containing the block.
set_param(gcb, 'UserDataPersistent', 'on');
Note If persistent UserData for a block contains any Simulink data objects, the directories containing the definitions for the classes of those objects must be on the MATLAB path when you open the model containing the block.
returns the run-time object of the currently selected block. Note Virtual blocks do not have run-time objects. Blocks eliminated during model compilation as an optimization also do not have run-time objects. A run-time object exists only while the model containing the block is running or paused. If the model is stopped, get_param returns an empty handle. When you stop or pause a model, all existing handles for run-time objects become empty.
at the MATLAB command line. This Simulink model contains the S-function adapt_lms.m, which performs a system identification to determine the coefficients of an FIR filter. The S-functions PostPropagationSetup method initializes the block run-time objects DWork vector such that the second vector stores the filter coefficients calculated at each time step. In the Simulink model, double-clicking on the annotation below the S-function block executes its OpenFcn. This function first opens a figure for plotting the FIR filter coefficients. It then executes the function add_adapt_coef_plot.m to add a PostOutputs method execution event to the S-functions block run-time object using the following lines of code.
% Get the full path to the S-function block blk = 'sldemo_msfcn_lms/LMS Adaptive'; % Attach the event-listener function to the S-function h = add_exec_event_listener(blk, ...
The function plot_adapt_coefs.m is registered as an event listener that is executed after every call to the Sfunctions Outputs method. The function accesses the block run-time objects DWork vector and plots the filter coefficients calculated in the Outputs method. The calling syntax used in plot_adapt_coefs.m follows the standard needed for any listener. The first input argument is the S-functions block run-time object, and the second argument is a structure of event data, as shown below.
function plot_adapt_coefs(block, eventData) % The figure's handle is stored in the block's UserData hFig = get_param(block.BlockHandle,'UserData'); tAxis = findobj(hFig, 'Type','axes'); tAxis = tAxis(2); tLines = findobj(tAxis, 'Type','Line'); % The filter coefficients are stored in the block run-time % object's second DWork vector. est = block.Dwork(2).Data; set(tLines(3),'YData',est);
However, the displayed data may not be the blocks true output if the run-time object is not synchronized with the Simulink execution. Simulink only ensures the run-time object and Simulink execution are synchronized when the run-time object is used either within a Level-2 MATLAB S-function or in an event listener callback. When called at the MATLAB command line, the run-time object can return incorrect output data if other blocks in the model are allowed to share memory. To ensure the Data field contains the correct block output, turn off the Signal storage reuse option on the Optimization pane in the Configuration Parameters dialog box.
Process View
The following figures show the order in which the Simulink engine invokes the callback methods in an Sfunction. Solid rectangles indicate callbacks that always occur during model initialization or at every time step. Dotted rectangles indicate callbacks that may occur during initialization and/or at some or all time steps during the simulation loop. Each callback method determine the exact circumstances under which the engine invokes the callback. (See the documentation) The process view diagrams represent the execution of S-functions that contain continuous and discrete states, enable zero-crossing detection, and reside in a model that uses a variable-step solver. Different solvers omit certain steps in the diagram. For a better understanding of how the Simulink engine executes a particular Sfunction, run the model containing the S-function using the Simulink debugger. The model initialization loop In the following model initialization loop, the Simulink engine configures the S-function for an upcoming simulation.
The engine always makes the required calls to mdlInitializeSizes and mdlInitializeSampleTime to set up the fundamental attributes of the S-function, including input and output ports, S-function dialog parameters, work vectors, sample times, etc. The engine calls additional methods, as needed, to complete the S-function initialization. For example, if the S-function uses work vectors, the engine calls mdlSetWorkWidths. Also, if the mdlInitializeSizes method deferred setting up input and output port attributes, the engine calls any methods necessary to complete the port initialization, such as mdlSetInputPortWidth, during signal propagation. The mdlStart method calls the mdlCheckParameters and mdlProcessParameters methods if the S-function uses dialog parameters. The mdlInitializeSizes callback method also runs when you enter the name of a compiled S-function into the SFunction Block Parameters dialog box.
The model simulation loop After initialization, the Simulink engine executes the following simulation loop. If the simulation loop is interrupted, either manually or when an error occurs, the engine jumps directly to the mdlTerminate method. If the simulation was manually halted, the engine first completes the current time step before invoking mdlTerminate. If your model contains multiple S-Function blocks, the engine invokes a particular method for every Sfunction before proceeding to the next method. For example, the engine calls all the mdlInitializeSizes methods before calling any mdlInitializeSampleTimesmethods. The engine uses the block sorted order to determine the order to execute the S-functions.
Data View
S-function blocks have input and output signals, parameters, and internal states, plus other general work areas. In general, block inputs and outputs are written to, and read from, a block I/O vector. Inputs can also come from External inputs via the root Inport blocks Ground if the input signal is unconnected or grounded
Block outputs can also go to the external outputs via the root Outport blocks. In addition to input and output signals, S-functions can have Continuous states Discrete states Other working areas such as real, integer, or pointer work vectors
You can parameterize S-function blocks by passing parameters to them using the S-Function Block Parameters dialog box. The following figure shows the general mapping between these various types of data.
Figura 4: How the Simulink engine interacts with C MEX S-functions from data perspective An S-functions mdlInitializeSizes routine sets the sizes of the various signals and vectors. S-function methods called during the simulation loop can determine the sizes and values of the signals.
that you. It might be helpful to examine some sample S-functions. Code for the examples is stored in the following folder under the MATLAB root folder. toolbox/simulink/simdemos/simfeatures
Remove any other registered callback methods from your copy of the template file. In the calls to RegBlockMethod, the first input argument is the name of the S-function API method and the second input argument is the function handle to the associated local function in the MATLAB S-function.
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 objects NumContStates property. Do not initialize discrete states in the setup method. Step 3 Initialize the discrete states in the PostPropagationSetup method. A Level-2 MATLAB 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. Step 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 values 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 states initial condition to the value of the S-functions 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;
Step 5 Calculate the S-functions 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;
Step 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. Step 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;
Step 8 Perform any cleanup, such as clearing variables or memory, in the Terminate method. Unlike C MEX Sfunctions, Level-2 MATLAB S-function are not required to have a Terminate method.
block.InputPortSameDimsAsOutputPort(a,b); %Configure DWork a to have its size reset when input size changes. block.DWorkRequireResetForSignalSize(a,true); function SetInputDimsMode(block, port, dm) % Set dimension mode block.InputPort(port).DimensionsMode = dm; block.OutputPort(port).DimensionsMode = dm; function setOutputVarDims(block, opIdx, inputIdx) % Set current (run-time) dimensions of the output outDimsAfterReset = block.InputPort(inputIdx(1)).CurrentDimensions; block.OutputPort(opIdx).CurrentDimensions = outDimsAfterReset;
The following table gives overview of the features supported by Level-2 MATLAB S-functions and Level-1 MATLAB S-functions.
References
Simulink 7 Users Guide. COPYRIGHT 19902010 by The MathWorks, Inc. Simulink 7 Developing S-Functions. COPYRIGHT 19982010 by The MathWorks, Inc. Simulink 7 Reference. COPYRIGHT 20022010 by The MathWorks, Inc.