Sei sulla pagina 1di 21

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)

Working with Data Objects


About Data Object Classes
Note This section uses the term data to refer generically to signals and parameters. The Simulink software uses objects called data classes to define the properties of specific types of data objects. The classes also define functions, called methods, for creating and manipulating instances of particular types of objects. A set of built-in classes are provided for specifying specific types of Attributes. Memory structures called packages are used to store the code and data that implement data classes. The classes provided by the Simulink software reside in the Simulink package. Classes provided by products

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.

About Data Object Methods


Data classes define functions, called methods, for creating and manipulating the objects that they define. A class may define any of the following kinds of methods. Dynamic Methods A dynamic method is a method whose identity depends on its name and the class of an object specified implicitly or explicitly as its first argument. You can use either function or dot notation to specify this object, which must be an instance of the class that defines the method or an instance of a subclass of the class that defines the method. For example, suppose class A defines a method called setName that assigns a name to an instance of A. Further, suppose the MATLAB workspace contains an instance of A assigned to the variable obj. Then, you can use either of the following statements to assign the name 'foo' to obj:
obj.setName('foo'); setName(obj, 'foo');

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.

About Object Properties


Object properties are variables associated with an object that specify properties of the entity that the object represents, for example, the size of a data type. The objects class defines the names, value types, default values, and valid value ranges of the objects properties. You can use either the Model Explorer or MATLAB commands to change a data objects properties

Handle Versus Value Classes


Simulink data object classes fall into two categories: value classes and handle classes. About Value Classes The constructor for a value class returns an instance of the class and the instance is permanently associated with the MATLAB variable to which it is initially assigned. Reassigning or passing the variable to a function causes MATLAB to create and assign or pass a copy of the original object. For example, Simulink.NumericType is a value class. Executing the following statements
>> x = Simulink.NumericType; >> y = x;

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]

Saving and Loading Data Objects


You can use the save command to save data objects in a MAT-file and the load command to restore them to the MATLAB workspace in the same or a later session. Definitions of the classes of saved objects must exist on the MATLAB path for them to be restored. If the class of a saved object acquires new properties after the object is saved, Simulink adds the new properties to the restored version of the object. If the class loses properties after the object is saved, only the properties that remain are restored.

Using Data Objects in Simulink Models


You can use data objects in Simulink models as parameters and signals. Using data objects as parameters and signals allows you to specify simulation and code generation options on an object-by-object basis.

Creating Persistent Data Objects


To create parameter and signal objects that persist across Simulink sessions, first write a script that creates the objects or create the objects with the Simulink Data Class Designer or at the command line and save them in a MAT-file. Then use either the script or a load command as the PreLoadFcn callback routine for the model that uses the objects. For example, suppose you save the data objects in a file named data_objects.mat and the model to which they apply is open and active. Then, entering the following command
set_param(gcs, 'PreLoadFcn', 'load data_objects');

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.

Associating User Data with Blocks


You can use the set_param command to associate your own data with a block. For example, the following command associates the value of the variable mydata with the currently selected block.
set_param(gcb, 'UserData', mydata)

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.

Accessing Block Data During Simulation


About Block Run-Time Objects
Simulink provides an application programming interface, called the block run-time interface, that enables programmatic access to block data, such as block inputs and outputs, parameters, states, and work vectors, while a simulation is running. You can use this interface to access block run-time data from the MATLAB command line, the Simulink Debugger, and from Level-2 MATLAB S-functions Note You can use this interface even when the model is paused or is running or paused in the debugger. The block run-time interface consists of a set of Simulink data object classes whose instances provide data about the blocks in a running model. In particular, the interface associates an instance of Simulink.RunTimeBlock, called the blocks run-time object, with each nonvirtual block in the running model. Run-time objects methods and properties provide access to run-time data about the blocks I/O ports, parameters, sample times, and states. The Simulink.RunTimeBlock class allows a Level-2 MATLAB S-function or other MATLAB program to obtain information about a block. Simulink software passes the object to the callback methods of Level-2 MATLAB S-functions when it updates or simulates a model, allowing the callback methods to get blockrelated information from and provide such information to Simulink software. You can also use instances of this class in MATLAB programs to obtain information about blocks during a simulation. For a summary of a run-time objects methods and properties see the following tables.

Simulink.RunTimeBlock property summary

Simulink.RunTimeBlock method summary

Accessing a Run-Time Object


Every nonvirtual block in a running model has a RuntimeObject parameter whose value, while the simulation is running, is a handle for the blocks run-time object. This allows you to use get_param to obtain a blocks run-time object. For example, the following statement
rto = get_param(gcb,'RuntimeObject');

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.

Listening for Method Execution Events


One application for the block run-time API is to collect diagnostic data at key points during simulation, such as the value of block states before or after blocks compute their outputs or derivatives. The block run-time API provides an event-listener mechanism that facilitates such applications. For an example of using method execution events, enter
sldemo_msfcn_lms

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);

Synchronizing Run-Time Objects and Simulink Execution


Run-time objects can be used at the MATLAB command line to obtain the value of a blocks output by entering the following commands.
rto = get_param(gcb,'RuntimeObject') rto.OutputPort(1).Data

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.

How the Simulink Engine Interacts with C MEX S-Functions


The Level-2 MATLAB S-function API corresponds closely to the API for creating C MEX S-functions. Like a Level-2 MATLAB S-function, a MEX S-function consists of a set of callback methods that the Simulink engine invokes to perform various block-related tasks during a simulation. MEX S-functions can be implemented in C, C++, or Fortran. The engine directly invokes MEX S-function routines instead of using function handles as with MATLAB S-functions. Because the engine invokes the functions directly, MEX Sfunctions must follow standard naming conventions specified by the S-function API. This section examines how the Simulink engine interacts with C MEX S-functions from two perspectives: Process perspective, i.e., at which points in a simulation the engine invokes the S-function. Data perspective, i.e., how the engine and the S-function exchange information during a simulation.

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.

Figura 2: The model initialization loop

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.

Figura 3: The model simulation loop

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.

Writing Level-2 MATLAB S-Functions


Use the basic Level-2 MATLAB S-function template msfuntmpl_basic.m to get a head start on creating a new Level-2 MATLAB S-function. The template contains skeleton implementation of the required callback methods defined by the Level-2 MATLAB S-function API. To write a more complicated S-function, use the annotated template msfuntmpl.m. To create a MATLAB 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. We recommend that you follow the structure and naming conventions of the templates when creating Level-2 MATLAB S-functions. This makes it easier for others to understand and maintain the MATLAB S-functions

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

Example of Writing a Level-2 MATLAB S-Function


The following steps illustrate how to write a simple Level-2 MATLAB S-function. When applicable, the steps include examples from the S-function demo 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. Step 1 Copy the Level-2 MATLAB S-function template msfuntmpl.m to your working folder. If you change the file name when you copy the file, change the function name in the function line to the same name. Step 2 Modify the setup method to initialize the S-functions attributes. For this example: Set the run-time objects NumInputPorts and NumOutputPorts properties to 1 in order to initialize one input port and one output port. Invoke the run-time objects SetPreCompInpPortInfoToDynamic and SetPreCompOutPortInfoToDynamic methods to indicate that the input and output ports inherit their compiled properties (dimensions, data type, complexity, and sampling mode) from the model. Set the DirectFeedthrough property of the run-time objects InputPort to false in order to indicate the input port does not have direct feedthrough. Retain the default values for all other input and output port properties that are set in your copy of the template file. The values set for the Dimensions, DatatypeID, and Complexity properties override the values inherited using the SetPreCompInpPortInfoToDynamic and SetPreCompOutPortInfoToDynamic methods. Set the run-time objects NumDialogPrms property to 1 in order to initialize one S-function dialog parameter. Specify that the S-function has an inherited sample time by setting the value of the runtime objects SampleTimes property to [-1 0]. Call the run-time objects RegBlockMethod method to register the following four callback methods used in this S-function.
PostPropagationSetup InitializeConditions Outputs Update

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.

Operations for Variable-Size Signals


Following are modifications to the Level-2 MATLAB S-functions template (msfuntmpl_basic.m) and additional operations that allow you to use variable-size signals.
function setup(block) % Register the properties of the output port block.OutputPort(1).DimensionsMode = 'Variable'; block.RegBlockMethod('SetInputPortDimensionsMode', @SetInputDimsMode); function DoPostPropSetup(block) %Register dependency rules to update current output size of output port a depending on %input ports b and c block.AddOutputDimsDependencyRules(a, [b c], @setOutputVarDims); %Configure output port b to have the same dimensions as input port a

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;

Available S-Function Implementations


You can implement your S-function in one of five ways: A Level-1 MATLAB S-function provides a simple MATLAB interface to interact with a small portion of the S-function API. Level-2 MATLAB S-functions supersede Level-1 MATLAB S-functions. A Level-2 MATLAB S-function provides access to a more extensive set of the S-function API and supports code generation. In most cases, use a Level-2 MATLAB S-function when you want to implement your S-function in MATLAB. A C MEX S-function provides the most programming flexibility. You can implement your algorithm as a C MEX S-function or write a wrapper S-function to call existing C, C++, or Fortran code. Writing a new S-function requires knowledge of the S-function API and, if you want to generate inlined code for the S-function, the Target Language Compiler (TLC).

What Type of S-Function Should You Use?


Consider the following questions if you are unclear about what type of S-function is best for your application.

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.

Potrebbero piacerti anche