8/9/2019 BAB16 - The User-Defined Funtions Library
1/14
Introduction to Simulink with Engineering Applications 16−1Copyright © Orchard Publications
Chapter 16
The User −Defined Functions Library
his chapter is an introduction to the User−Defined Functions Library. This is the fifteenthlibrary in the Simulink group of libraries and contains the blocks shown below. We willdescribe the function of each block included in this library and we will perform simulation
examples to illustrate their application.
8/9/2019 BAB16 - The User-Defined Funtions Library
2/14
Chapter 16 The User−Defined Functions Library
16−2 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
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) repre-sents the ith element of the vector; u(1) or u alone represents the first element. The specifiedexpression can consist of numeric constants, arithmetic operators, relational operators, logicaloperators, 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
(16.1)
is(16.2)
where the constants and can be evaluated from the initial conditions. Then we can com-
pute and display any value of by specifying , , and , 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 , , ,
and in MATLAB’s 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-
d2
y
dt2
-------- 4y+ 2ttan=
y 1 4 ⁄ ( ) 2t 2t 2ttan+sec( ) k 1 2t k 2 2tsin+cos+ln⋅cos–=
k 1 k 2
y t k 1 k 2
u 1( ) t π 6 ⁄ = = u 2( ) k 1 1–= = u 3( ) k 2 3–= =
8/9/2019 BAB16 - The User-Defined Funtions Library
3/14
Introduction to Simulink with Engineering Applications 16−3Copyright © 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 Func-tion block, or writing the function as an M−file S−function, then accessing it using the S−Func-tion block.
Example 16.2In the model of Figure 16.2, the function in the MATLAB Fcn block is specified as eig and out-
puts the eigenvalues of Matrix .
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 moreinformation and an example, please refer to the Simulink User’s Manual.
Example 16.3
In this example we will create a model using an Embedded MATLAB Function block to accept a
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
A
3 3×
8/9/2019 BAB16 - The User-Defined Funtions Library
4/14
Chapter 16 The User−Defined Functions Library
16−4 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
We double−click the Embedded MATLAB Function block to open it for editing, and the Embed-ded MATLAB Editor appears as shown in Figure 16.4.
Figure 16.4. The Embedded MATLAB Editor window
Using MATLAB’s 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 thedeterminant 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.
8/9/2019 BAB16 - The User-Defined Funtions Library
5/14
Introduction to Simulink with Engineering Applications 16−5Copyright © 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 MAT-LAB Edi tor , f rom the F i le menu we se lec t Save as Model , and we save i t asmatrix_det_inv01.mdl. The content of the modified Embedded MATLAB Editor is now asshown 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 Func-tion block appears as shown in Figure 16.6.
8/9/2019 BAB16 - The User-Defined Funtions Library
6/14
Chapter 16 The User−Defined Functions Library
16−6 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
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 defined in MATLAB’s 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 MATLAB’s 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 Figure16.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 EmbeddedMATLAB Run
−Time 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
A
8/9/2019 BAB16 - The User-Defined Funtions Library
7/14
Introduction to Simulink with Engineering Applications 16−7Copyright © Orchard Publications
The S− Function Block
16.4 The S− Function Block
The S− Function block provides access to S
−functions. The S
−function named as the S
−function
name parameter can be a Level−1 M−file or a Level−1 or Level−2 C MEX−file S−function. Weshould use the M−File S−Function block to include a Level−2 M−file S−function in a block dia-gram. This block is described in Section 11.18, Chapter 11, Page 11−43.
16.5 The Level−2 M−file S− Function Block
We introduced the S−
Function blocks in Section 11.18, Chapter 11, Page 11-43. We will nowdescribe some additional blocks.
A Level−2 M−file S−function is an M−file that defines the properties and behavior of an instanceof a Level−2 M−File S−Function block that references the M−file in a Simulink model.
The Level−2 M−file S− Function block allows us to use a Level−2 M−file S−function in a model.We do this by creating an instance of this block in the model. Then, we enter the name of theLevel−2 M−File S−function in the M−file name field of the block's parameter dialog box.
For a Level−1 M−file S−function we use the S−Function block.
To become familiar with this block, let us review the demos as we did in Section 11.17, Chapter11, Page 11-41. In MATLAB’s Command Window we type
sfundemos
and MATLAB will display the S−Function directory blocks shown in Figure 16.9. In this text wewill be concerned with the M−file S−Functions only.
Next, we double-click on the M−file S−Functions block of Figure 16.9 and MATLAB displays theLevel−1 and Level−2 M−file S−Functions shown in Figure 16.10.
8/9/2019 BAB16 - The User-Defined Funtions Library
8/14
Chapter 16 The User−Defined Functions Library
16−8 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
Figure 16.9. S−Function directory blocks
Figure 16.10. Levels of M−file S−Functions
The Level−1 M−file S−Functions are shown in Figure 16.11 and the Level−2 M−file S−Functionsare shown in Figure 16.12. We observe that the first 5 models of the Level−2 M−file S−Functionsand the same as those of the Level−1 M−file S−Functions but of course are implemented differ-ently in each case.
Figure 16.11. List of Level−1 M−file S−Functions
8/9/2019 BAB16 - The User-Defined Funtions Library
9/14
Introduction to Simulink with Engineering Applications 16−9Copyright © Orchard Publications
The Level−2 M−file S− Function Block
Figure 16.12. List of Level−2 M−file S−Functions
The Level−2 M−file S−function Application Programming Interface (API) allows us to use theMATLAB language to create custom blocks with multiple inputs and outputs and capable of han-dling any type of signal produced by a Simulink model, including matrix and frame signals of anydata type. The Level−2 M−file S-Functions resemble those defined by the C MEX−file S−func-tions and consist of a set of callback methods that Simulink invokes when updating or simulatingthe model. The callback methods perform the actual work of initializing and computing the out-puts of the block defined by the S−function. Thus, the Level−2 M−file S−function API specifies aset of callback methods that an M−file S−function must implement and others that it may chooseto omit, depending on the requirements of the block that the S−function defines.
To create an Level−2 M−file S−function, we can begin by making a copy of the template that Sim-ulink provides and edit the copy as necessary to reflect the desired behavior of the S-function youare creating. The comments in the template explain how it is done. To access this template, wedouble-click on the Level−2 M−file template block shown in Figure 16.11.
To access the Level−1 M−file S−function template, we double-click on the Level−1 M−file tem-plate block shown in Figure 16.10.
Table 16.1 lists the Level−2 M−file S−function callback methods and their C MEX−file equiva-lents.
8/9/2019 BAB16 - The User-Defined Funtions Library
10/14
Chapter 16 The User−Defined Functions Library
16−10 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
Example 16.4
Let us review the Level−1 M−file S−function file script for the Times two m−file shown in Figure16.11 above, and the Level−2 M−file S−function file script for the Times two m−file shown in Fig-ure 16.12 above. To view the script for these files denoted as sfundemo_timestwo, andmsfcn_times_two.m respectively, we double−click on the Times two blocks and on the annotated
blocks shown in green.The Level−1 M−file S−function file script for the Times two m−file is as shown below where wehave disabled the executable mex file. We observe that the script for this file has the same syntaxas 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
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 mdlDerivativesDisable 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 mdlRTWZeroCrossings mdlZeroCrossings
8/9/2019 BAB16 - The User-Defined Funtions Library
11/14
Introduction to Simulink with Engineering Applications 16−11Copyright © Orchard Publications
The Level−2 M−file S− Function 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 % matrixcase { 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 Level−2 M−file S−function file script for the Times two m−file is as shown below where weobserve 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 $
8/9/2019 BAB16 - The User-Defined Funtions Library
12/14
Chapter 16 The User−Defined Functions Library
16−12 Introduction to Simulink with Engineering Applications Copyright © Orchard Publications
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 S− Function Builder Block
The S− Function Builder block creates a C MEX−file S−function from specifications and C sourcecode that we provide. As stated earlier, we will not discuss C MEX−files in this text. To view someexamples we type
sfundemos
at the MATLAB Command window, and we choose the appropriate block from those shown inFigure 16.13 below.
8/9/2019 BAB16 - The User-Defined Funtions Library
13/14
Introduction to Simulink with Engineering Applications 16−13Copyright © Orchard Publications
The S− Function Examples Block
Figure 16.13. Examples of S−Functions
16.7 The S− Function Examples Block
The S− Function Examples block displays M−file S−Function, C−file S−Function, C++ S−Func-tion, Ada S−Function, and Fortran S−Function examples shown in Figure 16.13 above.
8/9/2019 BAB16 - The User-Defined Funtions Library
14/14
Chapter 16 The User−Defined Functions Library
16−14 Introduction to Simulink with Engineering ApplicationsCopyright © Orchard Publications
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 Sim-ulink model. This block accepts multiple input signals and produces multiple output signals.
• The S− Function block provides access to S−functions. The S−function named as the S−func-tion name parameter can be a Level−1 M−file or a Level−1 or Level−2 C MEX−file S−function.
• The Level−2 M−file S− Function block allows us to use a Level−2 M−file S−function in amodel.
• The S-Function Builder block creates a C MEX−file S−function from specifications and Csource code that we provide.
• The S− Function Examples block displays M−file S−Function, C−file S−Function, C++ S−Function, Ada S−Function, and Fortran S−Function examples.