Sunteți pe pagina 1din 14

Chapter 16

The UserDefined Functions Library

his chapter is an introduction to the UserDefined Functions Library. This is the fifteenth
library in the Simulink group of libraries and contains the blocks shown below. We will
describe the function of each block included in this library and we will perform simulation
examples to illustrate their application.

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

161

Chapter 16 The UserDefined Functions Library


16.1 The Fcn Block

The Fcn block applies a specified expression to its input denoted as u. If u is a vector, u(i) represents the ith element of the vector; u(1) or u alone represents the first element. The specified
expression can consist of numeric constants, arithmetic operators, relational operators, logical
operators, and the math functions abs, acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor,
hypot, ln, log, log10, pow, power, rem, sgn, sin, sinh, sqrt, tan, and tanh.

Example 16.1
It can be shown that the solution of the differential equation
2

is

d y
-------2- + 4y = tan 2t
dt

(16.1)

y = ( 1 4 ) cos 2t ln ( sec 2t + tan 2t ) + k 1 cos 2t + k 2 sin 2t

(16.2)

where the constants k 1 and k 2 can be evaluated from the initial conditions. Then we can compute and display any value of y by specifying t , k 1 , and k 2 , using the model shown in Figure 16.1.

Figure 16.1. Model for Example 16.1

For the model of Figure 16.1 we specified u ( 1 ) = t = 6 , u ( 2 ) = k 1 = 1 , u ( 3 ) = k 2 = 3 ,


and in MATLABs Command window we entered:
u(1)=pi/6; u(2)=1; u(3)=3;
y=(1/4)*cos(2*u(1))*log(sec(2*u(1))+tan(2*u(1)))+(2)*cos(2*u(1))+(3)*cos(2*u(1));

16.2 The MATLAB Fcn Block

The MATLAB Fcn block applies the specified MATLAB function or expression to the input.
This block is slower than the Fcn block because it calls the MATLAB parser during each integra-

162

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The Embedded MATLAB Function Block


tion step. As an alternative, we can use built-in blocks such as the Fcn block or the Math Function block, or writing the function as an Mfile Sfunction, then accessing it using the SFunction block.
Example 16.2
In the model of Figure 16.2, the function in the MATLAB Fcn block is specified as eig and outputs the eigenvalues of Matrix A .

Figure 16.2. Model for Example 16.2

16.3 The Embedded MATLAB Function Block

The Embedded MATLAB Function block contains a MATLAB language function in a Simulink
model. This block accepts multiple input signals and produces multiple output signals. For more
information and an example, please refer to the Simulink Users Manual.
Example 16.3
In this example we will create a model using an Embedded MATLAB Function block to accept a
3 3 matrix and output the value of its determinant and its inverse matrix.
We begin with a model that contains a Constant block, an Embedded MATLAB Function block,
and two Display blocks as shown in Figure 16.3. We save this model as matrix_det_inv.mdl

Figure 16.3. Blocks for the model for Example 16.3

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

163

Chapter 16 The UserDefined Functions Library


We doubleclick the Embedded MATLAB Function block to open it for editing, and the Embedded MATLAB Editor appears as shown in Figure 16.4.

Figure 16.4. The Embedded MATLAB Editor window

Using MATLABs Editor, we define a new function file as


function [det, inv] = matrix(A)

The contents of this function file as follows:*


function [det, inv] = matrix(A)
% This function computes the determinant and the inverse of a 3x3
% matrix A which must be defined in MATLAB's Command Window.
%
det=A(1,1)*A(2,2)*A(3,3)+A(1,2)*A(2,3)*A(3,1)+A(1,3)*A(2,1)*A(3,2)...
A(3,1)*A(2,2)*A(1,3)A(3,2)*A(2,3)*A(1,1)A(3,3)*A(2,1)*A(1,2);
%
% For a 3x3 matrix where A=[a11 a12 a13; a21 a22 a23; a31 a32 a33],
% the inverse of A is obtained as invA = (1/detA)*adjA where adjA
% represents the adjoint of A. Ref: Numerical Analysis, ISBN 0-9709511-1-6
% The cofactors are defined below.
%
b11=A(2,2)*A(3,3)A(2,3)*A(3,2);
b12=(A(2,1)*A(3,3)A(2,3)*A(3,1));
b13=A(2,1)*A(3,2)A(2,2)*A(3,1);
b21=(A(1,2)*A(3,3)A(1,3)*A(3,2));
b22=A(1,1)*A(3,3)A(1,3)*A(3,1);
b23=(A(1,1)*A(3,2)A(1,2)*A(3,1));
b31=A(1,2)*A(2,3)A(1,3)*A(2,2);
b32=(A(1,1)*A(2,3)A(1,3)*A(2,1));
b33=A(1,1)*A(2,2)A(1,2)*A(2,1);
%
% We must remember that the cofactors of the elemements of the ith
% row (column) of A are the elements of the ith column (row) of AdjA.
* The script for the user defined function used in this example is not the best choice. For the computation of the
determinant of a square matrix of any size, we could use for loops such as for i=1:n, and for the computation of
the inverse of a square matrix of any size, we can use the LU decomposition method.

164

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The Embedded MATLAB Function Block


% Accordingly, for the next statement below,we use the single quotation
% character (') to transpose the elements of the resulting matrix.
%
adjA=[b11 b12 b13; b21 b22 b23; b31 b32 b33]';
%
inv=(1/det)*adjA

We delete the contents shown in Figure 16.4, we copy the above script into the Embedded MATLAB Editor, from the File menu we select Save as Model, and we save it as
matrix_det_inv01.mdl. The content of the modified Embedded MATLAB Editor is now as
shown in Figure 16.5.

Figure 16.5. Function definition for the computation of the determinant and inverse of a 3x3 matrix

Next, we return to the model of Figure 16.3, and we observe that the Embedded MATLAB Function block appears as shown in Figure 16.6.

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

165

Chapter 16 The UserDefined Functions Library

Figure 16.6. Modified model for Example 16.3

Now, we connect the blocks shown in Figure 16.6 as shown in Figure 16.7 where in the Constant
block we have assigned matrix A defined in MATLABs Command window as
A=[1 2 3; 1 3 4; 1 4 3];

Figure 16.7. The connected blocks for the model of Example 16.3

Finally, in MATLABs Command Window we type and execute the command


matrix_det_inv01

After execution of the simulation command in Figure 16.7, the model appears as shown in Figure
16.8.

Figure 16.8. The model for Example 16.3 in its final form

The functions det(A) and inv(A) are defined in MATLAB but are not included in the Embedded
MATLAB RunTime Function Library List. This list includes common functions as sqrt, sin, cos,
and others. Thus, had we issued the simulation command without defining the function [det, inv]
= matrix(A), Simulink would have issued the following warnings:
Output det must be assigned before returning from the function
Output inv must be assigned before returning from the function

166

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The SFunction Block


16.4 The SFunction Block

The SFunction block provides access to Sfunctions. The Sfunction named as the Sfunction
name parameter can be a Level1 Mfile or a Level1 or Level2 C MEXfile Sfunction. We
should use the MFile SFunction block to include a Level2 Mfile Sfunction in a block diagram. This block is described in Section 11.18, Chapter 11, Page 1143.

16.5 The Level2 Mfile SFunction Block

We introduced the SFunction blocks in Section 11.18, Chapter 11, Page 11-43. We will now
describe some additional blocks.
A Level2 Mfile Sfunction is an Mfile that defines the properties and behavior of an instance
of a Level2 MFile SFunction block that references the Mfile in a Simulink model.
The Level2 Mfile SFunction block allows us to use a Level2 Mfile Sfunction in a model.
We do this by creating an instance of this block in the model. Then, we enter the name of the
Level2 MFile Sfunction in the Mfile name field of the block's parameter dialog box.
For a Level1 Mfile Sfunction we use the SFunction block.
To become familiar with this block, let us review the demos as we did in Section 11.17, Chapter
11, Page 11-41. In MATLABs Command Window we type
sfundemos

and MATLAB will display the SFunction directory blocks shown in Figure 16.9. In this text we
will be concerned with the Mfile SFunctions only.
Next, we double-click on the Mfile SFunctions block of Figure 16.9 and MATLAB displays the
Level1 and Level2 Mfile SFunctions shown in Figure 16.10.

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

167

Chapter 16 The UserDefined Functions Library

Figure 16.9. SFunction directory blocks

Figure 16.10. Levels of Mfile SFunctions

The Level1 Mfile SFunctions are shown in Figure 16.11 and the Level2 Mfile SFunctions
are shown in Figure 16.12. We observe that the first 5 models of the Level2 Mfile SFunctions
and the same as those of the Level1 Mfile SFunctions but of course are implemented differently in each case.

Figure 16.11. List of Level1 Mfile SFunctions

168

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The Level2 Mfile SFunction Block

Figure 16.12. List of Level2 Mfile SFunctions

The Level2 Mfile Sfunction Application Programming Interface (API) allows us to use the
MATLAB language to create custom blocks with multiple inputs and outputs and capable of handling any type of signal produced by a Simulink model, including matrix and frame signals of any
data type. The Level2 Mfile S-Functions resemble those defined by the C MEXfile Sfunctions and consist of a set of callback methods that Simulink 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 Sfunction. Thus, the Level2 Mfile Sfunction API specifies a
set of callback methods that an Mfile Sfunction must implement and others that it may choose
to omit, depending on the requirements of the block that the Sfunction defines.
To create an Level2 Mfile Sfunction, we can begin by making a copy of the template that Simulink provides and edit the copy as necessary to reflect the desired behavior of the S-function you
are creating. The comments in the template explain how it is done. To access this template, we
double-click on the Level2 Mfile template block shown in Figure 16.11.
To access the Level1 Mfile Sfunction template, we double-click on the Level1 Mfile template block shown in Figure 16.10.
Table 16.1 lists the Level2 Mfile Sfunction callback methods and their C MEXfile equivalents.

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

169

Chapter 16 The UserDefined Functions Library


TABLE 16.1 Level-2 M-file S-Function and corresponding C MEX-file callback methods
Level-2 M-file callback method

C MEX-file callback method

setup method (see Setup Method)

mdlInitializeSizes

CheckParameters

mdlCheckParameters

Derivatives

mdlDerivatives

Disable

mdlDisable

Enable

mdlEnable

InitializeCondition

mdlInitializeConditions

Outputs

mdlOutputs

ProcessParameters

mdlProcessParameters

SetInputPortComplexSignal

mdlSetInputPortComplexSignal

SetInputPortDataType

mdlSetInputPortDataType

SetInputPortDimensions

mdlSetInputPortDimensionInfo

SetInputPortSampleTime

mdlSetInputPortSampleTime

SetInputPortSamplingMode

mdlSetInputPortFrameData

SetOutputPortComplexSignal

mdlSetOutputPortComplexSignal

SetOutputPortDataType

mdlSetOutputPortDataType

SetOutputPortDimensions

mdlSetOutputPortDimensionInfo

SetOutputPortSampleTime

mdlSetOutputPortSampleTime

Start

mdlStart

Update

mdlUpdate

WriteRTW

mdlRTW

ZeroCrossings

mdlZeroCrossings

Example 16.4
Let us review the Level1 Mfile Sfunction file script for the Times two mfile shown in Figure
16.11 above, and the Level2 Mfile Sfunction file script for the Times two mfile shown in Figure 16.12 above. To view the script for these files denoted as sfundemo_timestwo , and
msfcn_times_two.m respectively, we doubleclick on the Times two blocks and on the annotated
blocks shown in green.
The Level1 Mfile Sfunction file script for the Times two mfile is as shown below where we
have disabled the executable mex file. We observe that the script for this file has the same syntax
as Example 11.14, Section 11.18, Chapter 11, Page 11-44.
function [sys,x0,str,ts] = timestwo(t,x,u,flag)
%TIMESTWO S-function whose output is two times its input.
%
This M-file illustrates how to construct an M-file S-function that
%
computes an output value based upon its input. The output of this

1610

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The Level2 Mfile SFunction Block


%
S-function is two times the input value:
%
%
y = 2 * u;
%
%
See sfuntmpl.m for a general S-function template.
%
%
See also SFUNTMPL.
%
%
Copyright 1990-2002 The MathWorks, Inc.
%
$Revision: 1.7 $
%
% Dispatch the flag. The switch function controls the calls to
% S-function routines at each simulation stage of the S-function.
%
switch flag,
%%%%%%%%%%%%%%%%%%
% Initialization %
%%%%%%%%%%%%%%%%%%
% Initialize the states, sample times, and state ordering strings.
case 0
[sys,x0,str,ts]=mdlInitializeSizes;
%%%%%%%%%%%
% Outputs %
%%%%%%%%%%%
% Return the outputs of the S-function block.
case 3
sys=mdlOutputs(t,x,u);
%%%%%%%%%%%%%%%%%%%
% Unhandled flags %
%%%%%%%%%%%%%%%%%%%
% There are no termination tasks (flag=9) to be handled.
% Also, there are no continuous or discrete states,
% so flags 1,2, and 4 are not used, so return an emptyu
% matrix
case { 1, 2, 4, 9 }
sys=[];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Unexpected flags (error handling)%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Return an error message for unhandled flag values.
otherwise
error(['Unhandled flag = ',num2str(flag)]);
end
% end timestwo

The Level2 Mfile Sfunction file script for the Times two mfile is as shown below where we
observe that only the required Level-2 N-file callback methods appearing in Table 16.1 are used.
function msfcn_times_two(block)
% Level-2 M file S-Function for times two demo.
%
Copyright 1990-2004 The MathWorks, Inc.
%
$Revision: 1.1.6.1 $

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

1611

Chapter 16 The UserDefined Functions Library


setup(block);
%endfunction
function setup(block)
%% Register number of input and output ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
%% Setup functional port properties to dynamically
%% inherited.
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.InputPort(1).DirectFeedthrough = true;
%% Set block sample time to inherited
block.SampleTimes = [-1 0];
%% Run accelerator on TLC
block.SetAccelRunOnTLC(true);
%% Register methods
block.RegBlockMethod('Outputs',

@Output);

%endfunction
function Output(block)
block.OutputPort(1).Data = 2*block.InputPort(1).Data;
%endfunction

16.6 The SFunction Builder Block

The SFunction Builder block creates a C MEXfile Sfunction from specifications and C source
code that we provide. As stated earlier, we will not discuss C MEXfiles in this text. To view some
examples we type
sfundemos

at the MATLAB Command window, and we choose the appropriate block from those shown in
Figure 16.13 below.

1612

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

The SFunction Examples Block

Figure 16.13. Examples of SFunctions

16.7 The SFunction Examples Block

The SFunction Examples block displays Mfile SFunction, Cfile SFunction, C++ SFunction, Ada SFunction, and Fortran SFunction examples shown in Figure 16.13 above.

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

1613

Chapter 16 The UserDefined Functions Library


16.8 Summary
The Fcn block applies a specified expression to its input denoted as u.
The MATLAB Fcn block applies the specified MATLAB function or expression to the input.
The Embedded MATLAB Function block contains a MATLAB language function in a Simulink model. This block accepts multiple input signals and produces multiple output signals.
The SFunction block provides access to Sfunctions. The Sfunction named as the Sfunction name parameter can be a Level1 Mfile or a Level1 or Level2 C MEXfile Sfunction.
The Level2 Mfile SFunction block allows us to use a Level2 Mfile Sfunction in a
model.
The S-Function Builder block creates a C MEXfile Sfunction from specifications and C
source code that we provide.
The SFunction Examples block displays Mfile SFunction, Cfile SFunction, C++ S
Function, Ada SFunction, and Fortran SFunction examples.

1614

Introduction to Simulink with Engineering Applications


Copyright Orchard Publications

S-ar putea să vă placă și