Home
Simulink User's Guide
Contents
1. Blocks a Triggered Subsystem Can Contain Triggered systems only execute at specific instances during a simulation As a result the only blocks that are suitable for use in a triggered subsystem are e Blocks with inherited sample time such as the Logical Operator block or the Gain block e Discrete blocks having their sample time set to 1 which indicates that the sample time is inherited from the driving block Triggered and Enabled Subsystems Triggered and Enabled Subsystems A third kind of conditionally executed subsystem combines both types of conditional execution The behavior of this type of subsystem called a triggered and enabled subsystem is a combination of the enabled subsystem and the triggered subsystem as shown by this flow diagram Trigger event the enable input signal gt 0 Don t execute the subsystem Execute the subsystem A triggered and enabled subsystem contains both an enable input port and a trigger input port When the trigger event occurs Simulink checks the enable input port to evaluate the enable control signal If its valueis greater than zero Simulink executes the subsystem If both inputs are vectors the subsystem executes if at least one element of each vector is nonzero The subsystem executes once at the time step at which the trigger event occurs Creating a Triggered and Enabled Subsystem You create a triggered and enabled subsystem by dragging bot
2. Scope Auto Scaling the Scope Axes This figure shows the same output after pressing the Auto scale toolbar button which automatically scales both axes to display all stored simulation data In this case the y axis was not scaled because it was already set to the appropriate limits EJ vdp Scope DAA A The Auto scale button 0 1 Time offset 0 If you click on the Auto scale button while the simulation is running the axes are auto scaled based on the data displayed on the current screen and the auto scale limits are saved as the defaults This enables you to use the same limits for another simulation Zooming in on Data You can zoom in on data in both the x and y directions at the same time or in either direction separately The zoom feature is not active while the simulation is running Tozoom in on data in both directions at the same time makesurethe left most Zoom toolbar button is selected Then define the zoom region using a bounding box When you release the mouse button the Scope displays the data in that 9 123 Scope 9 124 area This figure shows a region of the displayed data enclosed within a bounding box Ed vdp Scope DAA Al Zoom in both directions 0 10 Time offset 0 This figure shows the zoomed region which appears after you release the mouse button Ed vdp Scope DAA Ala 12 Time offset 0 To zoom in on data in just the x direction click on th
3. mdi Derivatives compute the derivatives static void mdlDerivatives double dx const double xx const double u Si mStruct S int tid x mdi Terminate called when the simulation is terminated static void mdlTerminate SimStruct S ifdef MATLAB MEX FILE ls this being compiled as MEX file include si mulink c MEX file interface mechanism else include cg_sfun h Code generation registration func endi f 8 31 8 S Functions 8 32 An important distinction between M file and C MEX file S functions is that C ME X file S functions must have calls tomd Update andmdl Derivative evenif there are no continuous or discrete states in the model Without these functions your ME X file will not compile successfully Examples of C MEX File S Function Blocks In general most S F unction blocks require the handling of states continuous or discrete The following sections discuss four common types of systems that you can model in Simulink with S functions e Continuous e Discrete e Hybrid e Variable step time All examples are based on the C MEX file S function template sf unt mpl c Example Continuous State S Function This example shows how to model a set of continuous state equations in C The example is calledcsfunc c and is located in thesi mul ink src directory x CSFUNC An example C file S function for defining a continuous system x Ax Bu y
4. This command simulates the vdp model for 1000 seconds saving the last 100 rows of thereturn variables Thesimulation outputs values for t and y only but saves the final state vector in a variable called xFi nal t x yl sim vdp 1000 simset MaxRows 100 Out putVariables ty FinalStateName xFinal simset simget 4 23 simset 4 24 Purpose Syntax Description Parameters Create or edit simulation parameters and solver properties for the si m command options simset property value options simset old_opstruct property value options simset old_opstruct new_opstruct simset Thesi mset command creates a structure called opti ons in which the named simulation parameters and solver properties have the specified values All unspecified parameters and properties take their default values It is only necessary to enter enough leading characters to uniquely identify the parameter or property Case is ignored for parameters and properties options simset property value sets the values of the named properties and stores the structure in options options simset old_opstruct property value modifies the named properties ino d_opstruct an existing structure options simset old_opstruct new_opstruct combines two existing options structures ol d_opstruct andnew_opstruct intoopti ons Any properties defined in new_opstruct overwrite the same properties
5. ifdef MATLAB _MEX_ FILE 1s this being compiled as a MEX file include simulink c MEX file interface mechanism else include cg_sfun h Code generation registration func endi f This is the C language equivalent of ds f unc m The updating of discrete state vector x occurs in md Update and the calculation of the outputs occurs in md Out puts Since there are no continuous states or tasks to complete at termination both md Derivatives and mdi Ter mi nate are empty functions Example Hybrid System S Functions Simulink includes a function called mi xedm c which is an example of a hybrid a combination of continuous and discrete states system modeled in an S function mi xedm c combines elements of csfunc c anddsf unc c If you have a hybrid model all you have to do is place your continuous equations in mdi Deri vative and your discrete equations in md Update In Simulink block diagram form the model looks like this o Q 5 z In Integrator Unit Delay Out 8 37 8 S Functions Hereisthecode for the C language S function mi xedm c which implements a continuous integrator followed by a discrete unit delay mixedm a C file S function that models a continuous integrator l s in series with a unit delay 1 z define S_FUNCTION_NAME mixedm include simstruc h mdlInitializeSizes initialize the sizes structure static void mdllnitializeSizes SimStruct S
6. Sample S Functions It is helpful to examine some sample S functions as you read the next sections Other examples are stored in these subdirectories under the MATLAB root directory e C MEX files si mul i nk src e M files tool box si mulink blocks Thesi mul ink blocks directory contains many M file S functions Consider starting off by looking at these files csfunc m dsfunc m vsfunc m mi xed m vdpm m si mom m simom2 m limintm m vlimintm m and vd mi ntm m W riting S Functions as M Files Writing S Functions as M Files An M filethat defines an S F unction block must provideinformation about the model Simulink needs that information during simulation As the simulation proceeds Simulink the ODE solver and the M file interact to perform specific tasks These tasks include defining initial conditions and block characteristics and computing derivatives discrete states and outputs Simulink provides a template M file S function that includes statements that define necessary functions as well as comments to help you write the code needed for your S function block This template file sf unt mpl m is in the directory t ool box si mulink blocks below the MATLAB root directory Defining S Function Block Characteristics For Simulink to recognize an M file S function you must provide it with specific information about the S function This information includes the number of inputs outputs states and oth
7. The reset port has direct feedthrough If the block output is fed back into this port either directly or through a series of blocks with direct feedthrough an algebraic loop results To resolve this loop feed the block state into the reset port instead To access the block s state select the Show state port check box Choosing All Options When all options are selected the icon looks like this Initial condition Discrete Time Integrator Discrete Time Integrator Parameters and Dialog Box Characteristics Discrete Time Integrator r Discrete Time Integrator Parameters Integrator method Extemal reset Discrete time integration of the input signal ForwardE uler v H Initial condition source Initial condition 0 T Limit output Upper saturation limit inf Lower saturation limit inf I Show saturation port T Show state port Sample time 1 Apply Revert internal h Direct Feedthrough Sample Time Scalar E xpansi States Vectorized Zero Crossing ports Discrete The integration method The default is ForwardE uler Resets the states to their initial conditions when a trigger event rising falling or either occurs in the reset signal Gets the states initial conditions from the Initial condition parameter if set to internal or from an external block if set to external The states initial conditio
8. You can change block parameter values in the workspace during a simulation and update the block diagram with these changes To dothis makethe changes in the command window then makethe model window the active window then choose Update Diagram from the Edit menu NOTE Most block parameter values must be specified as strings Two exceptions arethePosition andUserDat a parameters common to all blocks This command sets theSol ver and St opTi me parameters of thevdp system set_param vdp Solver odel5s StopTime 3000 This command sets the Gain of block Mu in thevdp system to 1000 stiff set_param vdp Mu Gain 1000 This command sets the position of the Fcn block in thevdp system set_param vdp Fcn Position 50 100 110 120 This command sets theZer os and Poles parameters for the Zero Pole block in the my model system set_param mymodel Zero Pole Zeros 2 4 Poles 1 2 3 This command sets theGai n parameter for a block in a masked subsystem The variablek is associated with the Gai n parameter set _param mymodel Subsystem k 10 set param This command sets the OpenFcn callback parameter of the block named Compute in system my mode The function my_open_fcn executes when the user double clicks on the Compute block For more information see Using Callback Routines on page 3 30 set_param mymodel Compute OpenFen my_open_fcn See Also get_para
9. 9 23 Coulomb and Viscous Friction Purpose Library Description Et 9 24 Parameters and Dialog Box Characteristics Model discontinuity at zero with linear gain elsewhere Nonlinear The Coulomb and Viscous Friction block models Coulomb static and viscous dynamic friction The block models a discontinuity at zero and a linear gain otherwise The offset corresponds to the Coulombic friction the gain corresponds to the viscous friction The block is implemented as y sign u Gain abs u Offset wherey is the output u is the input and Gai n andoffset are block parameters The block accepts one input and generates one output Coulomb amp Viscous Friction r Coulombic and Viscous Friction mask discontinuity offset at zero models coulomb friction Linear gain models viscous friction y sign x Gain abs x Offset Parameters Theoffset applied toall input values The default is 1 3 2 0 Coulomb friction value Offset 0320 Coefficient of viscous friction Gain Apply Revert Help f Direct Feedthrough Yes The signal gain at nonzero input points The default is 1 Sample Time Inherited from driving block Scalar Expansion No Vectori zed Yes Zero Crossing Yes at the point where the static friction is overcome Data Store Memory Purpose Library Description A Parameters and Dialog Box Characteristics Define a data s
10. Appendix C provides the contents of the SimStruct the data structure that describes S functions Although we have tried to provide the most complete and up to date information in this manual some information may have changed after it was printed Please check the Simulink LateBreaking News delivered with your Simulink system for the latest release notes Professional Application Toolboxes Professional Application Toolboxes Oneof the key features of Simulink is that it is built atop MATLAB Asa result Simulink users have direct access tothe wide range of MATLAB based tools for generating analyzing and optimizing systems implemented in Simulink These tools include MATLAB Application Toolboxes specialized collections of M files for working on particular classes of problems Toolboxes are more than just collections of useful functions they represent the efforts of some of the world s top researchers in fields such as controls signal processing and system identification MATLAB Application Toolboxes therefore let you stand on the shoulders of world class scientists All toolboxes are built using MATLAB This has some very important implications for you e Every toolbox builds on the robust numerics rock solid accuracy and years of experience in MATLAB e You get seamless and immediate integration with Simulink and any other toolboxes you may own e Because all toolboxes are written in MATLAB code you can take a
11. Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion Of the gain States 0 Vectorized Yes Zero Crossing No State Space Purpose Library Description w Act Bu y CxtDu Implement a linear state space system Linear The State Space block implements a system whose behavior is defined by x Ax Bu y Cx Du where x is the state vector u istheinput vector and y is the output vector The matrix coefficients must have these characteristics as illustrated in the diagram below A must bean n by n matrix where n is the number of states B must be an n by m matrix where m is the number of inputs e C must bean r by n matrix wherer is the number of outputs e D must bean r by m matrix n m n A B r C D The block accepts one input and generates one output The input vector width is determined by the number of columns in the B and D matrices The output vector width is determined by the number of rows in the C and D matrices Simulink converts a matrix containing zeros to a sparse matrix for efficient multiplication 9 137 State Space Parameters State Space r State Space and Dia log State space model dx dt Ax Bu Box y Cx Du Parameters The matrix coefficients E u e L Initial conditions 0 Apply Revert Help Characteristics Direct Feedthrough OnlyifD 0 The initial state vector Sample Time Contin
12. Setting Values for sizes Structure Fields Each macro call has two arguments the first is thesSi mSt ruct structure identifier 5 and the second is the data value For example the following statements definethesi zes structure for an S function static void mdll nitializeSizes SimStruct S ssSetNumContStates S 1 ssSetNumDiscStates S 0 ssSetNumOutputs S 1 ssSetNuml nputs S 1 ssSetDirectFeedThrough S 0 ssSetNumSampleTi mes S 1 This code specifies that the block has one continuous state and no discrete states one output and one input no direct feedthrough and one sample time a continuous block must still define a sample time of zero A Simple C MEX File Example Writing S Functions as M Files on page 8 11 started with a simple example that doubled the amplitude of an input signal The example below does the same thing except that it is written in C ME X file format Feje Sine Wave S Function Scope 8 29 8 S Functions 8 30 TheC codethat contains the S function is modeled on a Simulink S function template called sf unt mpl c Using this template you can create a C function by following the structure provided Below isthe MATLAB codeinti mest wo c the C code that contains the S function TIMESTWO An example C S function for multiplying an input by 2 y 2 x define S_FUNCTION_NAME ti mest wo include simstruc h mdlInitializeSizes initialize the size
13. This figure shows two models The subsystem on the left contains two Inport blocks and one Outport block The Subsystem block on the right shows the labeled ports Int Outi p In2 Subsystem Subsystem with Inport and Outport blocks Subsystem with labeled ports 3 29 3 Creating a M odel Using Callback Routines You can define MATLAB expressions that execute when the block diagram or a block is acted upon in a particular way These expressions called callback routines are associated with block or model parameters For example the callback associated with a block s OpenFcn parameter is executed when the model user double clicks on that block s name or path changes To define callback routines and associate them with parameters use the set _ param command described on page 11 22 For example this command evaluates the variablet est var when the user double clicks on the Test block in my model set_param mymodel Test OpenFcn testvar You can examinethec ut ch system cl ut ch mdi for routines associated with many model callbacks These tables list the parameters for which you can define callback routines and indicate when those callback routines are executed Routines that are executed before or after actions take place occur immediately before or after the action Table 3 1 Model Callback Parameters Parameter When Executed CloseFcn Before the block diagram is closed PostLoadFcn After th
14. ssSetPWorkVal ue S pworkl dx pworkVal ue ssGet User Dat a S ssSetUserData S userDataPtr ssGet T S Get size of pointer work vector Set size of pointer work vector Get number of S function parameters Set number of S function parameters Get specific S function parameter Get number of sample times Set number of sample times Get input vector Get state vector Get derivative vector Get continuous state for disabled subsystem Get pointer to integer work vector Get integer work vector element value Set integer work vector element value Get pointer to real work vector Get real work vector element value Set real work vector element value Set pointer to pointer work vector Get pointer work vector element value Set pointer work vector element value Get user defined pointer value Set user defined pointer value Get the simulation time C The SimStruct Macro Description ssGetTaskTi me S sti ssGetTStart S ssGetTFinal S ssi sMinorTi meSt ep S ss sMaj or Ti meSt ep S ssGet Si mTi meStep S ssSetStopRequested S val ssGetSol verName S ssGetStepSize 5 ssSetSolverNeedsReset S ssGetSampl eTi me S sti ssSetSampl eTi me S sti ssGet OffsetTime S sti ssSetOffsetTi me S sti ssSetTNext S tnext d ssIsSampleHit S sti ssIisfirstinitCond Used for multirate S functions to get the task time of a specific sample time index Get simulation sta
15. Constant Goto From Display The signal label and propagated label before updating the diagram 2 Che De Constant Goto From Display The same signal labels after updating the diagram In thenext example the propagated signal label shows the contents of a vector signal This figure only shows the label after updating the diagram Display Constant2 3 23 reating a M odel gt c 3 24 Annotations Annotations provide textual information about a model You can add an annotation to any unoccupied area of your block diagram For example This sample model shows a constant signal Annotations being input to a Scope Constant Scope This block generates a constant signal with a value of 1 This block displays its input graphically in a window that looks like an oscilloscope To create a model annotation double click on an unoccupied area of the block diagram A small rectangle appears and the cursor changes to an insertion point Start typing the annotation contents Each line is centered within the rectangle that surrounds the annotation To move an annotation drag it to a new location To edit an annotation select it Toreplace the annotation on a Microsoft Windows or X Windows system click on the annotation then double click or dragthe cursor to select it Then enter the new annotation On a Macintosh select the annotation then enter new text Toinsert characters click b
16. Description Themdl nitializeCondi tions function initializes the S function s states and work vectors Simulink calls this function at the beginning of the simulation The initial states are defined in parameter x0 For hybrid blocks continuous states precede discrete states as described in the illustration in Setting the Initial Conditions on page 8 47 The work vectors if any have already been allocated by Simulink and initialized to all zeros Any additional initialization should be done in this function For more information about setting initial conditions see page 8 47 Example static void mdllnitializeConditi ons double x0 SimStruct S Get real RWork and integer I Work work vectors double RWork int Work i dsIndex nStates x Initialize the continuous states to all ones for i 0 i lt ssGetNumCont States S i x0 i 1 0 8 56 mdllnitializeConditions x Initialize all the discrete states to minus one Note the discrete states immediately follow x the continuous states in the x0 vector dsl ndex ssGetNumCont States S nStates ssGetNumTotal States S for i dsIndex i lt nStates i x0 i 1 0 x Initialize the real work vector to 2 0 RWork ssGetRWork S for i 0 i lt ssGetNumRWork S i RWork i 2 0 Initialize the integer work vector to 3 IWork ssGet Work S for i 0 i lt ssGetNuml W
17. auto go 54 of f ScopeData on 5000 qo off g A Sample M odel File Block BlockType Name Position Amplitude Frequency Phase Sampl eTi me Block BlockType Name Position VariableName Buffer Decimation Sampl eTi me Block BlockType Name Position ShowPortLabels MaskType MaskDescription MaskHelp MaskPromptString MaskStyleString MaskVariables MaskDisplay MasklconFrame MasklconOpaque MasklconRotate Masklconlnits Sin Sine Wave 100 100 130 130 go go ng lye ToWorkspace To Workspace 305 160 365 190 simout inf Jo q SubSystem mx b 195 97 230 133 on Sampl eMaskedBl ock Models the equation for a line y mx b nThe slope and intercept are mask block parameters Enter the slope m and intercept b in the dialog box parameter fields nThe block generates y for a given input x Slope intercept edit edit m 1 b 2 plot 0 1 0 m m lt 0 on on off normalized B M odel File Format MaskValueString 32 System Name mx b Location 561 354 851 509 Open of f ScreenCol or white Block BlockType Inport Name x Position 50 50 70 70 Port 1 Port Width Eat Sampl eTi me al Block BlockType Constant Name Constant Position 110 103 140 127 Value p Block BlockType Gain Na me Gain Position 110 45 140
18. ssSetNumRWor k S 3 real work vector ssSetNuml Work Sarai integer work vect ssSet NumP Work S 0 pointer work vect ssSetNuml nput Ar gs y 1 input arguments ssSetNumSampl eTi mes 3 sample times mdlOutputs Purpose Compute output vector Declaration static void mdi Out puts double y double x double u SimStruct S int tid Arguments double y The output vector returned double x The states vector double u Theinput vector SimStruct 5 Thesimstruct for this block int tid Thetask ID for use with multitasking real time operating systems Description The mdi Out puts function computes the S Function block output which is a function of time the states and the input as shown in the equation below y Solt x u Theinput arguments are the current states the current inputs thesi mStruct anda task ID The task ID is used when the system is executing ina multithreaded environment Example static void mdi Out put s double y double x double u SimStruct S int tid int i I x Compute the outputs that are a function of the continuous states for i 0 i lt ssGetNumContStates S i ylil x i 8 61 mdlOutputs I Compute the outputs that are a function of the discrete states if sslsSampleHitEvent S 0 tid int dsIndex nStates dsindex ssGetNumContStates nStates ssGetNumTotal States S for i dsIndex i l
19. y k 1 T 2 u k 1 then we have x k 1 y k y k T 2 x u k clip if necessary x k T 2 u k clip if necessary Here x k 1 is the best estimate of the next output It isn t quite the state in the sense that x k y k When T is variable that is obtained from the triggering times we have x k 1 y k y k x k T 2 u k u k 1 dip if necessary With this method input port 1 has direct feedthrough The block icon reflects the selected integration method as this figure shows T Tz T z 1 p pb p z 1 z 1 2 z 1 DT Int DT Int DT Int Fonward Euler Backward Euler Trapezoidal Discrete Time Integrator Defining Initial Conditions You can define the initial conditions as a parameter on the block dialog box or input them from an external signal To define the initial conditions as a block parameter specify the Initial condition source parameter as internal and enter the value in the Initial condition parameter field To provide the initial conditions from an external source specify the Initial condition source parameter as external An additional input port appears under the block input as shown in this figure Input U Output Initial condition BE z 1 Discrete Time Integrator Using the State Port Intwoknown situations you must usethe state port instead of the output port When the output of the block is fed back into the block through the reset port or the initial condi
20. 0 Rounding Function Rounding Operator Function floor ceil round fix Saturation Sat urate UpperLi mit Upper limit scalar or vector 0 5 LowerLi mit Lower limit scalar or vector 0 5 S Fundion S Funct i on Functi onName S function name name system Parameters S function parameters additional parameters if needed Sign Si gnum no block specific parameters A 18 Block Specific Parameters Table A 6 Nonlinear Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Switch Swi t ch Threshold Threshold Transport Delay Transport Del ay Del ayTi me Time delay Initiallnput Initial input BufferSize Initial buffer size Trigonometric Function Trigonometry Operator Function Variable Transport Delay VariableTransportDelay Maxi mumDel ay Maximum delay Initiallnput Initial input Maxi mumPoi nts Buffer size scalar or vector 0 scalar or vector 1 scalar or vector 0 scalar 1024 sin cos tan asin acos atan atan2 sinh cosh tanh scalar or vector 10 scalar or vector 0 scalar 1024 Table A 7 Sinks Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Display Display Format Format short long short_e long_e bank Deci mation Decimation scalar 1 Floating Floating display off on Sampl eTi me Sample time scalar Sample period 1 or vector period off
21. 5 16 Trim Analysis values for x u andy The underlying method is Sequential Quadratic Programming 5 17 Trim Analysis 5 18 Using Masks to Customize Blocks Introduction 2 5 62 A Sample Masked Subsystem 63 Creating Mask Dialog Box Prompts nn 64 Creating the Block Description and Help Text nn 6 6 Creating the Block Icon nn 66 Summary 2 2 ee ee 68 The Mask Editor An Overview 69 The Initialization Page whe oe de we ook po LOR LO Prompts and Associated Variables a ey a Re cal are tah up car a OR LO Control Types posk so ak 1 6 12 Default Values for Masked Block Parameters aoaaa a 6 14 Initialization Commands a 6 14 The Icon Page nn S O17 Displaying Text on the Block Icon nn 617 Displaying Graphics onthe Block Icon 16 18 Displaying a Transfer Function on the Block Icon 2 20 6 19 Controlling Icon Properties a 2 2 2 2 2 nn nn nn 620 The Documentation Page 624 The Mask TypeField 2 2 2 m nn nn 4 2 624 The Block Description Field 2 22 2 2 nn nn 624 The Mask Hep Text Fidd 6 25 6 Using M asks to Customize Blocks 6 2 Introduction Masking is a powerful Simulink feature that enables you to customize the dialog box and icon for a subsystem With masking you can Simplify the use of your model by replacing many dialog boxes in a subsystem with a sin
22. Apply Reven Help Close If you specify a matrix of time and input values the first column is a vector of time values Remaining columns are data at those time values where each column supplies data for an Inport block in port number order If necessary Simulink interpolates input data for time values not in the time vector If you specify a function the function is evaluated at each time step to generate one or more inputs 9 79 Inport e Tosupply external inputs from the workspace using thes i m command You can read data from the workspace using theut argument t x yl sim system timespan options ut If the system has more than one Inport block ut is a matrix or function as described in the preceding point e To provide a means for perturbation of the model by the i nmod andt rim analysis functions Inport blocks define the points where inputs are injected into the system For information about using Inport blocks with analysis commands see Chapter 5 Parameters r Inport and Dialo g Provides an input port for a subsystem or model The Box Sample time parameter may be used to specify the rate at which a signal enters the system Parameters Port number 1 The port number of the Inport block Port width 1 for dynamically sized g g 4 The width of theinput signal to the Inport Specify 1 to have it automatically determined Sample time 1 The rate at
23. Axx Bxu end of mdl Update function sys mdl Outputs t x u A B C D sys C x Dau end of mdli Outputs 8 19 8 S Functions 8 20 The above example conforms to the simulation stages discussed earlier in this chapter The system discrete state equations are of the form x n l Ax n Bu n y n Cx n Du n so that very general sets of difference equations can be modeled using dsfunc m This is similar to the built in Discrete State Space block You can usedsfunc masa starting point for modeling discrete state space systems with time varying coefficients Example Hybrid System S Functions Simulink includes a function called mi xedm m which is an example of a hybrid system a combination of continuous and discrete states modeled in an S function Handling hybrid systems is fairly straightforward thef ag parameter forces the calls to the correct S function subroutine for the continuous and discrete parts of the system One subtlety of hybrid S functions or any multirate S function is that Simulink calls themd Update mdi Out put and md Get Ti me Of Next Var Hi t routines at all sampletimes This means that in these routines you must test to determine which sample hit is being processed and only perform updates that correspond to that sample hit mi xed m models a continuous ntegrator followed by a discrete Unit Delay In Simulink block diagram form the model looks like this 1 HE q In In
24. Chirp Signal Sine wave with increasing frequency Parameters Initial frequency Hz 0 1 Target time secs 100 Frequency at target time Hz 1 Apply Revert Help The initial frequency of the signal specified as a scalar or vector value The default is 0 1 Hz The time at which the frequency reaches the Frequency at target time parameter value a scalar or vector value Thefrequency continues to change at the same rate after this time The default is 100 seconds The frequency of the signal at the target time a scalar or vector value The default is 1 Hz Sample Time Scalar Expansion Vectorized Zero Crossing Continuous Of parameters Yes No Clock Purpose Library Description Dialog Box Characteristics Display and provide the simulation time Sources The Clock block outputs the current simulation time at each simulation step When the block is opened this timeis displayed in the window Running a simulation with this block open slows down the simulation The Clock block is useful for other blocks that need the simulation time When you need the current time within a discrete system usethe Digital Clock block a ae Sample Time Continuous Scalar Expansion N A Vectorized No Zero Crossing No 9 19 Combinatorial Logic 9 20 Purpose Library Description ise Implement a truth table Nonlinear The Combinatorial Logic block implements a standard
25. Double click on the S F unction block to open the dialog box r Function User definable block Blocks may be written in M C or Fortran and must conform to S function standards tx u and flag are automatically passed to the S function by SIMULINK Extra parameters may be specified in the S function parameters field Parameters Enter the function name here In this example typet i mest wo S function name timestwo S function parameters If you have additional parameters to pass tothe block enter their names here separating them Apply Revert Help with commas In this example there are no addi You can now run this simulation tional parameters W riting S Functions as M Files Examples of M File S Functions The simple example discussed above has no states Most S Function blocks require the handling of states whether continuous or discrete The sections that follow discuss four common types of systems you can model in Simulink using S functions e Continuous e Discrete e Hybrid e Variable step All examples are based on the M file S function template found in sf unt mp m Example Continuous State S Function Simulink includes a function called csf unc m which is an example of a continuous state system modeled in an S function Here is the code for the M file S function function sys x0 str ts csfunc t x u flag CSFUNC An example M file S function for def
26. FixedStep Max Order Out put Option Out put Ti mes LoadExternallnput Externallnput SaveTi me Ti meSaveName SaveState StateSaveName SaveOut put Out put SaveName LoadInitialState InitialState SaveFinal State Final Stat eNa me Limit MaxRows Max Rows Decimation AlgebraiclLoopMsg MinStepSizeMsg Unconnectedl nput Msg UnconnectedOut put Msg UnconnectedLineMsg ConsistencyChecking ZeroCross BlockDefaults Orientation ForegroundColor BackgroundColor DropShadow NamePlacement FontName FontSize Font Wei ght FontAngle ShowName auto 5 RefineOutputTi mes pp off Et u on tout off xout on yout off xinitial off xFi nal off 1000 go warning warning warning warning warning off on right black white off normal Helvetica 10 normal normal on B M odel File Format AnnotationDefaults Horizontal Alignment Vertical Alignment ForegroundCol or BackgroundColor DropShadow Font Name FontSize Font Wei ght FontAngle System Name Location Open ScreenColor Block Bl ockType Name Position Floating Location Open Grid TickLabels ZoomMode Ti meRange YMin YMax SaveToWorkspace SaveName Li mi t Max Rows MaxRows Deci mation Samplelnput SampleTi me center middle black white off Helvetica 10 normal normal mask_example 628 63 1128 323 on white Scope Scope 305 100 335 130 off 188 365 512 604 off on on on
27. MATLABFcn MATLABFcn Out put Width Memory Memory X0 Inherit SampleTi me MinMax Mi nMax Function Inputs Vector of input values Vector of output values 2 D Row Column Table Function MATLAB function Output width Initial condition Inherit sampletime Function Number of input ports Multiport Switch Mul ti PortSwitch Inputs Number of inputs vector 5 5 vector tanh 5 5 vector vector 2 D matrix exp log logl0 square sqrt pow reciprocal hypot rem mod MATLAB function sin scalar or vector 1 scalar or vector 0 off on min max scalar 1 scalar or vector 3 A 17 A Model and Block Parameters Table A 6 Nonlinear Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Product Product Inputs Number of inputs scalar 2 Quantizer Quant izer Quantizationinterval Quantization interval scalar or vector 0 5 Rate Limiter Rat eLi miter RisingSlewLi mit Rising slew rate scalar or vector 1 FallingSl ewLi mit Falling slew rate scalar or vector 1 Relational Operator Rel ati onal Operator Operator Operator lt lt gt gt Relay Rel ay OnSwitchValue Switch on point scalar or vector eps Off SwitchVal ue Switch off point scalar or vector eps OnOut put Value Output when on scalar or vector 1 Of f Out put Val ue Output when off scalar or vector
28. Models the equation for a line y mx b The slope and intercept are mask block parameters Parameters Slope 3 Intercept Block help Enter the slope m and intercept b in the block dialog box parameter fields The block generates y for a given input x ay rer Sven Help Apply Revert Unmask Help Close The Mask Type Field The mask type is a block classification used only for purposes of documentation It appears in the block s dialog box and on all Mask Editor pages for the block Y ou can choose any name you want for the mask type When Simulink creates the block s dialog box it adds mask after the mask type to differentiate masked blocks from built in blocks The Block Description Field The block description is informative text that appears in the block s dialog box in the frame under the mask type If you are designing a system for others to use this is a good place to describe the block s purpose or function The Documentation Page Simulink automatically wraps long lines of text You can force line breaks by using the Enter or Return key The Mask Help Text Field You can provide help text that gets displayed when the Help button is pressed on the masked block s dialog box If you create models for others to use this is a good placeto explain how the block works and how to enter its parameters You can include user written documentation for a masked block s help
29. Rosen The signal frequency The default is 1 1 Unite j The signal units Hertz or radians sec The nits Hertz x default is Hertz Apply Revert Help Sample Time Inherited Scalar Expansion Of parameters Vectorized Yes Zero Crossing No 9 133 Sine Wave Purpose Library Description Po 9 134 Generate a sine wave Sources The Sine Wave block provides a sinusoid The block can operate in either continuous or discrete mode The output of the Sine Wave block is determined by y Amplitudex sin frequency x time phase The value of the Sample time parameter determines whether the block operates in continuous mode or discrete mode e 0 the default causes the block to operate in continuous mode e gt 0 causes the block to operate in discrete mode e 1 causes the block to operate in the same mode as the block receiving the signal Using the Sine Wave Block in Discrete Mode A Sample time parameter value greater than zero causes the block to behave as if it were driving a Zero Order Hold block whose sample time is set to that value Using the Sine Wave block in this way allows you to build models with sine wave sources that are purely discrete rather than models that are hybrid continuous discrete systems H ybrid systems areinherently more complex and as a result take longer to simulate The Sine Wave block in discrete mode uses an incremental algorithm rather than one based on absolute time As a resu
30. Simulink directly calls the correct S function routine for the current simulation stage A template S function written in C called sf unt mpl c located under si mul ink src is supplied with Simulink For a more amply commented version of the template sees f unt mpl doc inthe same directory NOTE Werecommend that you use the M file or C MEX file template when developing S functions 8 7 8 S Functions S Function Concepts Understanding these key concepts should enable you to build S functions correctly e Direct feedthrough e Dynamically sized inputs e Setting sample times and offsets e Initial sample times Direct Feedthrough Direct feedthrough means that the output or the variable sample time is controlled directly by the value of an input port A good rule of thumb is that an S function has direct feedthrough if e tsoutput md Out puts isafunction of theinput u Outputs may alsoinclude graphical outputs as in the case of an XY Graph scope e tis a variable sample time S function calls md Get Ti meOf Next Var Hit and the computation of the next sample hit requires the input u It is very important to set the direct feedthrough flag correctly because it affects the execution order of the blocks in your model and is used to detect algebraic loops Dynamically Sized Inputs S functions can be written to support arbitrary width inputs In this case the actual input width is determined dynamically when
31. The input vector must be monotonically increasing Parameters Vector of input values 5 5 Vector of output values tanhl 5 5 Apply Revert Help Direct Feedthrough Yes The vector of values containing block output values This vector must be the same size as the input vector Sample Time Inherited from driving block Scalar Expansion No Vectori zed Yes Zero Crossing No Look Up Table 2 D Purpose Library Description A Perform piecewise linear mapping of two inputs Nonlinear The Look Up Table 2 D block maps the block inputs to an output using linear interpolation of a table of values defined by the block s parameters You define the possible output values as the Table parameter Y ou define the values that correspond to its rows and columns with the Row and Column parameters The block generates an output value by comparing the block inputs with the Row and the Column parameters The first input identifies a row and the second input identifies a column as shown by this figure Row Column lA Table value Look Up Table 2 D The block generates output based on the input values e If theinputs match row and column parameter values the output is thetable value at the intersection of the row and column e If the inputs do not match row and column parameter values the block generates output by linearly interpolating between the appropriate table values If either or both blo
32. You can specify any of the following for the masked block help text e URL specification a string starting with http www file ftp or mailto e web command launches a browser e eval command evaluates a MATLAB string e Static text displayed in the web browser Simulink examines the first line of the masked block help text If it detects a URL specification web command or eval command it accesses the block help as directed otherwise the full contents of the masked block help text are displayed in the browser These examples illustrate several acceptable commands web docroot My Blockset Doc get_param gcb MaskType html eval Word My_Spec doc http www mathworks com file c mydir helpdoc htm www mathworks com Simulink automatically wraps long lines of text 6 25 6 Using M asks to Customize Blocks 6 26 Conditionally Executed Subsystems Introduction Enabled Subsystems Creating an Enabled Subsystem Blocks an Enabled Subsystem Can Contain Triggered Subsystems si Creating a Triggered Subsystem Function Call Subsystems i Blocks a Triggered Subsystem Can Contain Triggered and Enabled Subsystems Creating a Triggered and Enabled Subsystem A Sample Triggered and Enabled Subsystem 7 2 7 3 7 5 7 9 7 10 7 10 7 11 7 11 7 12 7 Conditionally Executed Subsystems 7 2 Introduction A conditionally executed subsyst
33. are by definition continuous Constant blocks for example Constant are by definition constant Discrete blocks e g Zero Order Hold Unit Delay Discrete Transfer Fcn etc have sample times that are explicitly specified by the user on the block dialog boxes All other blocks have implicitly defined sample times that are based on the sample times of their inputs For instance a Gain block that follows an Inte grator is treated as a continuous block whereas a Gain block that follows a Zero Order Hold is treated as a discrete block having the same sample time as the Zero Order Hold block For blocks whose inputs have different sample times if all sample times are integer multiples of the fastest sample time the block is assigned the sample time of the fastest input If a variable step solver is being used the block is assigned the continuous sample time If a fixed step solver is being used and the greatest common divisor of the sample times the fundamental sample time can be computed it is used Otherwise continuous is used It is important to note that Mux and Demux blocks are simply grouping operators signals passing through them retain their timing information F or this reason the lines emanating from a Demux block may have different colors if they are driven by sources having different sample times In this case the Mux and Demux blocks are color coded as hybrids yellow to indicate that they handle signals with
34. left or right by selecting the block and pressing the arrow keys Blocks You can copy or move blocks to compatible applications such as word processing programs using the Copy Cut and Paste commands These commands copy only the graphic representation of the blocks not their parameters Moving blocks from one window to another is similar to copying blocks except that you hold down the Shift key while you select the blocks You can usethe Undo command from the Edit menu to remove an added block Moving Blocks in a Model To move a single block from one place to another in a model window drag the block to a new location Simulink automatically repositions lines connected to the moved block To move more than one block including connecting lines 1 Select the blocks and lines If you need information about how to select more than one block see Selecting More than One Object on page 3 4 2 Drag the objects to their new location and release the mouse button Duplicating Blocks in a Model You can duplicate blocks in a model by following this step e Microsoft Windows and X Windows While holding down the Ctrl key select the block with the left mouse button then drag it to a new location You can also do this by dragging the block using the right mouse button e Macintosh While holding down the Option key select the block and drag it to a new location Duplicated blocks have the same parameter values as the o
35. line search and rank one updates to a J acobian matrix of partial derivatives Although the method is robust it is possible to create loops for which the loop solver will not converge without a good initial guess for the algebraic states z You can specify an initial guess for a linein an algebraic loop by placing an IC block which is normally used to specify an initial condition for a signal on that line As shown above another way to specify an initial guess for a line in an algebraic loop is to use an Algebraic Constraint block Whenever possible use an IC block or an Algebraic Constraint block to specify an initial guess for the algebraic state variables in a loop Invariant Constants Blocks either have explicitly defined sample times or inherit their sample times from blocks that feed them or are fed by them Simulink assigns Constant blocks a sample time of infinity also referred to as a constant sampletime Other blocks have constant sample time if they receive their input from a Constant block and donot inherit the sample time of another block This means that the output of these blocks does not change during the simulation unless the parameters are explicitly modified by the model user For example in this model both the Constant and Gain blocks have constant sample time Constant P Gain Discrete Time Scope Integrator Because Simulink supports the ability to change block parameters during a simulation all blocks even b
36. on off on off Pixel Autoscale Normalized cell array of strings delimited string A 23 A Model and Block Parameters A 24 When you use the Mask Editor to create a dialog box parameter for a masked block you provide this information e The prompt which you enter in the Prompt field e The variable that holds the parameter value which you enter in the Variable field e The type of field created which you specify by selecting a Control type e Whether the value entered in thefield is to be evaluated or stored as a literal which you specify by selecting an Assignment type Themask parameters listed in the table on the previous page store the values specified for the dialog box parameters in these ways e The Prompt field values for all dialog box parameters are stored in the MaskPrompt String parameter as a string with individual values separated by a vertical bar as shown in this example Slope Intercept e The Variable field values for all dialog box parameters are stored in the MaskVariables parameter as a string with individual assignments separated by a semi colon A sequence number indicates which prompt is associated with a variable A special character preceding the sequence number indicates the Assignment type indicates Evaluate amp indicates Literal For example a 1 b amp 2 indicates that the value entered in the first parameter field is assigned to variablea a
37. or any element of a vector control signal changes from 0 to a nonzero value For example this figure shows when rising R and falling F triggers occur for the given control signal A simple example of a trigger subsystem is illustrated below Sine Wave F im In Out Trigger Signal simout Subsystem gr To Workspace 1 In Trigger 1 _ 1 zZ Out Unit Delay In this example the subsystem is triggered on the rising edge of the square wave trigger control signal 7 8 Triggered Subsystems Creating a Triggered Subsystem You create a triggered subsystem by copying the Trigger block from the Connections library into a subsystem Simulink adds a trigger symbol and a trigger control input port to the Subsystem block icon Subsystem To select the trigger type open the Trigger block dialog box and select one of the choices for the Trigger type parameter as shown in the dialog box below e rising forces a trigger whenever the trigger signal crosses zero in a positive direction e falling forces a trigger whenever thetrigger signal crosses zeroin a negative direction e either forces a trigger whenever the trigger signal crosses zero in either direction Trigger Trigger Port Place this block in a subsystem to create a triggered subsystem Parameters Trigger type rising sind T Show output ting either Epp function ca
38. popup 6 13 Copy menu item 3 6 3 7 copy definition 3 13 CopyFcn block callback parameter 3 31 copying block parameters 3 6 3 7 blocks 3 6 blocks from block library 2 7 library block into a model 3 14 signal labels 3 22 Coulomb and Viscous Friction block 9 24 Create Mask menu item 6 9 Create Subsystem menu item 3 28 9 141 creating annotations 3 24 block libraries 3 13 first mask prompt 6 11 masked block descriptions 6 6 masked block icons 6 6 models 3 3 11 18 signal labels 3 22 subsystems 3 27 3 32 current block 11 14 current block handle 11 15 current system 11 16 Cut menu item 3 7 3 8 D Data Store Memory block 9 25 Data Store Read block 9 26 Data Store Write block 9 27 dbstop if error command 6 16 dbstop if warning command 6 16 Dead Zone block 9 28 zero crossings 10 6 deadband 9 12 debugging initialization commands 6 16 decimation factor 4 24 saving simulation output 4 15 decision tables modeling 9 20 default solvers 4 8 values for masked block parameters 6 14 defining mask type 6 6 6 24 masked block descriptions 6 24 masked block help text 6 6 delaying and holding input signals 9 159 input by specified sample time 9 164 input by variable amount 9 160 Delete key 3 8 3 22 3 24 delete block command 11 10 delete line command 11 11 Del eteFcn block callback parameter 3 31 deleting annotations 3 24 blocks 3 8 11 10 lines 11 11 mask prompts 6 11 signal labels 3 22 demo model running 2 2 Demos library 9
39. sim model timespan options ut pl pn t x yl y2 yn sim model timespan options ut pl pn Description Thesi m command simulates the specified Simulink model integrating the system of ordinary differential equations that describe the model For block diagram models only the model parameter is required Values for all parameters specified as an empty matrix are taken from the simulation parameter settings Any optional parameters specified in the command override the settings associated with the model For M file and MEX file S functions the model andti mespan parameters are required For models with continuous states theso ver parameter must be specified usingthesi ms et command described on page 4 24 For models with no continuous states the solver defaults toVari abl eStepDiscrete Arguments t Returned time vector x Returned state matrix containing continuous states followed by discrete states y Returned output matrix For block diagram models each column contains the output from a root level Outport block in port number order If any Outport block has a vector input its output takes the appropriate number of columns yl yn Can only be specified for block diagram models n is the number of root level Outport blocks Each output is returned in the corresponding yi mo del Name of a block diagram or MEX file or M file S function timespan Simulation start and stop time Specify as one
40. subsystem block If the block name includes a newline or carriage return specify the block name as a string vector and uses printf n as the newline character For example these lines assign the newline character toc r then get the value for the Signal Generator s Amplitude parameter cr sprintf n get_param untitled Signal cr Generator Amplitude ans 1 If the block name includes a slash character you repeat the slash when you specify the block name For example to get the value of the Location parameter for the block named Signal Noise in the my model system get_param mymodel Signal Noise Location 11 3 add_ block Purpose Add a block to a Simulink system Syntax add_block src dest add_block src dest parameterl valuel Description add_block src dest copies the block with full path name src toa new block with full path name dest The block parameters of the new block are identical to those of the original The name pui t in can be used asa source system name for all Simulink built in blocks blocks available in Simulink block libraries that are not masked blocks add_block src dest_obj parameterl valuel creates a copy as above in which the named parameters have the specified values Any additional arguments must occur in parameter value pairs Examples This command copies the Scope block from the Sinks subsystem of the si mu
41. u 2 TheC language style expression appliedtothe input Expression components are listed above The expression must be mathematically well formed i e matched parentheses proper number of function arguments etc Parameters Expression sin u Pexp 2 3 u 2 Apply Revert Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion No Vectori zed No Zero Crossing No First Order Hold Purpose Library Description A Parameters and Dialog Box Characteristics Implement a first order sample and hold Discrete The First Order Hold block implements a first order sample and hold that operates at the specified sampling interval This block has little value in practical applications and is included primarily for academic purposes You can see the difference between the Zero Order Hold and First Order Hold blocks by running the demo programf oh de mo This figure compares the output from a Sine Wave block and a First Order Hold block First Order Hold First Order Hold mask First Order Hold Parameters Sample time Apply Revert Help Direct Feedthrough No The time interval between samples Sample Time Continuous Scalar Expansion No States 1 continuous and 1 discrete per input element Vectorized Yes Zero Crossing No 9 63 From 9 64 Purpose Library Description gt Accept input from a Goto block
42. 0 nennen nn 3 11 Scalar Expansion of Inputs and Parameters 3 11 Using Drop Shadows saaana eaa 3 12 LibrarieS ccc cc eee eee 3 13 Terminology 0 0 cece eee 3 13 Creating a Library ese denia ai a Eao aaa Ea ai doia a eek 3 13 Modifying a Library 0 0 cece eee 3 14 Copying a Library Block intoa Model 0 3 14 Updating a Linked Block 0 000 eee eee 3 15 Breaking a Link toa Library Block 05 3 15 Finding the Library Block for a Reference Block 3 16 Getting Information About Library Blocks 3 16 Eines anna een aid 3 17 Drawing a Line Between Blocks 2 222 r nern 3 17 Drawing a Branch Line 0 cee eee ees 3 18 Drawing a Line Segment rennen nenn 3 18 Displaying Line Widths 0 0 0 eee eee 3 21 Signal Labels 0 cceec cence eee eee 3 22 Using Signal Labels 0 000 c eee ee 3 22 Signal Label Propagation 0 cee eee eee 3 23 Annotations zsunnuunnnnnn nun nun nun nn nn nun 3 24 Summary of Mouse and Keyboard Actions 5 3 25 Creating Subsystems z unnnnnnnnnon nn nn nn nun nun 3 27 Creating a Subsystem by Adding the Subsystem Block 3 28 Creating a Subsystem by Grouping Existing Blocks 3 28 Labeling Subsystem Ports 00 0c cece eee eee 3 29 Using Callback Routines 222222 rennen eee 3 30 Tips for Bu
43. 0 m Iftheslopeis negative Icon properties thelineis shifted up by 1 to keep it within the visible drawing area of the block The drawing commands have access to all of the variables in the mask workspace As different values of slope are entered the icon automatically updates the slope of the plotted line Selecting Normalized as the Drawing coordinates parameter located at the bottom of the list of icon properties specifies that the icon is drawn in a frame whose bottom left corner is 0 0 and whose top right corner is 1 1 This parameter is described later in this chapter 6 7 6 Using M asks to Customize Blocks Summary This discussion of the steps involved in creating a sample mask introduced you to these tasks e Defining dialog box prompts and their characteristics e Defining the masked block description and help text e Defining the command that creates the masked block icon The remainder of this chapter discusses the Mask Editor in more detail The M ask Editor An O verview The Mask Editor An Overview To mask a subsystem you can only mask Subsystem blocks select the Subsystem block then choose Mask Subsystem from the Edit menu The Mask Editor appears The Mask Editor consists of three pages each handling a different aspect of the mask The Initialization page enables you to define and describe mask dialog box parameter prompts name the variables associated with the parameters and specif
44. 1 2 1 3 1 5 1 10 1 10 1 12 1 12 1 14 1 14 1 14 1 15 1 G etting Started To the Reader 1 2 Welcome to Simulink In the last few years Simulink has become the most widely used software package in academia and industry for modeling and simulating dynamical systems Simulink encourages you to try things out You can easily build models from scratch or take an existing model and add toit Simulations are interactive so you can change parameters on the fly and immediately see what happens You have instant access to all of the analysis tools in MATLAB so you can take the results and analyze and visualize them We hope that you will get a sense of the fun of modeling and simulation through an environment that encourages you to pose a question model it and see what happens With Simulink you can move beyond idealized linear models to explore more realistic nonlinear models factoring in friction air resistance gear slippage hard stops and the other things that describe real world phenomena It turns your computer into a lab for modeling and analyzing systems that simply wouldn t be possible or practical otherwise whether the behavior of an automotive clutch system the flutter of an airplane wing the dynamics of a predator prey model or the effect of the monetary supply on the economy Simulink is also practical With thousands of engineers around the world using it to model and solv
45. 1 3 Input Port Width Input port width scalar 3 Subsystem SubSyst em ShowPortLabels Show Hide Port Labels on off Format menu item Terminator Ter mi nat or no block specific parameters Trigger Tri ggerPort TriggerType Trigger type rising falling either function call ShowOut put Port Show output port off on Width Wi dt h no block specific parameters Table A 4 Discrete Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Discrete Filter DiscreteFilter Numerator Numerator vector 1 Denomi nat or Denominator vector 1 2 Sampl eTi me Sample time Discrete Time Integrator Discretel ntegrator IntegratorMethod Integrator method ExternalReset External reset scalar sample period 1 or vector period offset ForwardEuler BackwardEuler Trapezoidal none rising falling either A 12 Block Specific Parameters Table A 4 Discrete Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values nitial ConditionSource nitial Condition Limit Output UpperSaturati onLimit LowerSaturationLimit ShowSat urationPort ShowStatePort Sampl eTi me Initial condition source Initial condition Limit output Upper saturation limit Lower saturation limit Show saturation port Show state port Sample time Discrete State Space Di screteStateSpace A B C D X0 Sampl eTi
46. 11 Discrete BIOCKS 1 ce tenes 10 11 Sample Time 2 0000 eee 10 11 Purely Discrete Systems 0 cee ee 10 11 Multirate Systems 0 00 cee een nn 10 12 vii Sample Time Colors 0 ccc tannie kanai 10 13 Mixed Continuous and Discrete Systems 10 15 Model Construction Commands 2 Introduction zuunnunnnnnnnun nun nun nn nun 11 2 How to Specify Parameters for the Commands 11 3 How to Specify a Path for a Simulink Object 11 3 Model and Block Parameters A Introduction ccc eee eee A 2 Model Parameters sunnnunnnnunnnnn nun nn nun A 3 Common Block Parameters 00 00eeeeeee eens A 7 Block Specific Parameters 0 cc cece eee eens A 10 Mask Parameters 00 cceeeeee eee A 23 Model File Contents zsn2eeennnnnnn nn nn nn nn nn nn B 2 The Model Section ccc eee eee nennen B 3 The BlockDefaults Section 0 0 ce ee nennen B 3 The AnnotationDefaults Section 0 ee B 3 The System Section 0 cece ees B 3 viii Contents A Sample Model File The SimStruct x Contents Getting Started To the Reader What Is Simulink How to Use This Manual Professional Application Toolboxes The Simulink Real Time ar Key Features The Real Time m Ada Extension Key Features Blocksets The DSP Blockset e The Fixed Point Blockset The Nonlinear Control Design Blockset
47. 3 Demux block 9 30 Derivative block 9 34 linearization 5 5 derivatives calculating 9 34 10 3 derivatives calculating for continuous states 8 55 derivatives limiting 9 113 description of masked blocks 6 24 Index Diagnostics page of Simulation Parameter dialog box 4 17 diagonal line segments 3 18 diagonal lines 3 17 Digital Clock block 9 36 direct feedthrough 10 2 S functions 8 8 disabled subsystem output 7 4 disabling zero crossing detection 4 18 10 5 disconnecting blocks 3 10 discontinuities detecting 5 11 trim function 5 16 zero crossings 10 3 Discrete block library 9 4 block parameters A 12 discrete blocks 10 11 in enabled subsystem 7 5 in triggered systems 7 10 Discrete Filter block 9 37 Discrete Pulse Generator block 9 39 discrete solver 4 8 4 9 4 10 discrete state S function example 8 18 8 35 discrete states updating 8 64 Discrete State Space block 9 40 discrete state space model 5 10 Discrete Transfer F cn block 9 48 9 159 Discrete Zero Pole block 9 50 Discrete Time Integrator block 9 42 sample time colors 10 15 discrete time systems 10 11 linearization 5 10 disp command 6 17 Display Alphabetical List menu item 3 43 Display block 9 57 Display Hierarchical List menu item 3 43 displaying graphics on masked block icons 6 18 line widths 3 21 output trajectories 5 2 output values 9 57 signals graphically 9 121 text on masked block icons 6 17 transfer functions on masked block icons 6 19 vector signals
48. 9 121 X Y plot of signals 9 163 dlinmod function 5 4 5 9 5 10 dlinmod2 function 5 9 Documentation page of Mask Editor 6 9 Dormand Prince formula 4 9 Dormand Prince pair 4 8 Dot Product block 9 59 dpol y command 6 19 dragging blocks 2 8 drawing coordinates 6 22 Autoscale 6 22 Normalized 6 7 6 22 Pixel 6 22 droots command 6 20 drop shadows 3 12 DSP Blockset 1 14 duplicating blocks 3 7 dynamically sized inputs 8 8 DYNAMI CALLY_ SIZED macro 8 43 E edit control type 6 12 editing annotations 3 24 block names 3 9 mask prompts 6 11 models 3 3 signal labels 3 22 1 5 Index 1 6 eigenvalues of linearized matrix 5 10 either trigger type 7 9 Elementary Math block algebraic loops 10 7 Enable block 9 60 creating enabled subsystems 7 3 outputting enable signal 7 5 states when enabling 7 5 enabled subsystems 7 2 7 3 9 60 initializing states in S function 8 47 setting states 7 4 ending Simulink session 3 45 EPS file printing to 3 41 equations modeling 3 34 equilibrium point 5 13 equilibrium point determination 5 7 error message parameter undefined 6 20 error tolerance 4 11 simulation accuracy 4 20 simulation speed 4 19 Euler s method 4 10 eval command and masked block help 6 25 Evaluate Assignment type 6 10 examples Clock block 5 3 continuous state S function 8 15 8 32 continuous system 3 35 converting Celsius to Fahrenheit 3 34 discrete state S function 8 18 8 35 equilibrium point determination 5 7 hybrid sy
49. 9 136 Solver page of Simulation Parameters dialog box 4 6 solver properties specifying 4 24 Index solvers 4 7 4 10 changing during simulation 4 2 choosing 4 4 default 4 8 discrete 4 8 4 9 4 10 fixed step 4 7 4 9 odel 4 10 ode113 4 9 4 19 odel5s 4 8 4 9 4 12 4 19 4 20 ode2 4 10 ode23 4 9 ode23s 4 9 4 12 4 20 ode3 4 10 ode4 4 9 ode45 4 8 ode5 4 9 specifying usingsi mset command 4 26 variable step 4 7 4 8 Sources block library 2 7 9 3 block parameters A 21 spectral analysis of nonlinear systems 9 18 speed of simulation 4 19 Spline Toolbox 1 9 square wave generating 9 132 ss2tf function 5 12 ss2zp function 5 12 ssGet WorkVal ue macro 8 49 ssGet PWorkVal ue macro 8 49 ssGet RWorkVal ue macro 8 49 sslsSamplehHit macro 8 46 ssSetl WorkVal ue macro 8 49 ssSetNumCont States macro 8 48 ssSetNumDiscStates macro 8 45 8 48 ssSetNuml nput Args macro 8 44 ssSetNuml Work macro 8 49 ssSetNumP Work macro 8 49 ssSetNumRWork macro 8 49 ssSetNumSamp eTi mes macro 8 47 ssSetOffsetTi me macro 8 45 ssSet PWorkVal ue macro 8 49 ssSet RWorkVal ue macro 8 49 ssSetSampl eTi me macro 8 45 stairs function 10 12 stair step function passing signal through 9 109 Start menu item 2 2 2 12 3 35 4 4 start time 4 7 StartFcn block callback parameter 3 32 Start Fen model callback parameter 3 30 starting Simulink 3 2 state derivatives setting to zero 5 13 state events 10 3 state space in discrete system 9 40 states
50. Block Name Purpose Display Scope Stop Simulation To File To Workspace XY Graph Show the value of the input Display signals generated during a simulation Stop the simulation when the input is nonzero Write data toa file Write data to a matrix in the workspace Display an X Y plot of signals using a MATLAB figure window Table 9 3 Discrete Library Blocks Block Name Purpose Discrete Filter Discrete State Space Discrete Time Integrator Discrete Transfer Fcn Implement IIR and FIR filters Implement a discrete state space system Perform discrete time integration of a signal Implement a discretetransfer function The Simulink Block Libraries Table 9 3 Discrete Library Blocks Continued Block Name Purpose Discrete Zero Pole First Order Hold Unit Delay Zero Order Hold Implement a discrete transfer function specified in terms of poles and zeros Implement a first order sampleand hold Delay a signal one sample period Implement zero order hold of one sample period Table 9 4 Linear Library Blocks Block Name Purpose Derivative Dot Product Gain Integrator Matrix Gain Slider Gain State Space Sum Transfer F cn Zero Pole Output the time derivative of the input Generate the dot product Multiply block input Integrate a signal Multiply the input by a matrix Vary a scalar gain using a slider Implement a linear state space syst
51. Building a Simple M odel the blocks in the library In the Sources library all blocks are signal sources The Sources library window looks like this i Library simulink S ou jo x File Edit Simulatic Format Tools Eu Constant LY Ramp Discrete Pulse Pulse Chirp Signal Generator Genera Clock Sequence A itor 12 34 p Digital Clock untitled mat From File T U From Workspace NM 3 Y Random Uniform Random Band Limited Number Numbe r White Noise the Sine Wave block You add blocks to your model by copying them from a block library or from another model For this exercise you need to copy the Sine Wave block To do this position the cursor over the Sine Wave block then press and hold down 2 Q uick Start the mouse button Notice how Simulink draws an outline around the block and its name Library simulink Sou Of x Eile Edit Simulation Format Tools ooon o e ID Constant Signal Step Generator r 7 Le Wh Ramp Sine Wave Repeating Sequence np ur AM Discrete Pulse Pulse Chirp Signal Generator Generator 12 34 Clock Digital Clock luntitled math T U From File From Workspace W MO Mi Random Uniform Random Band Limited Number Number White Noise Now dragthe block intothe model window As you movetheblock y
52. Connections TheFrom block accepts a signal from its corresponding Goto block then passes it as output From and Goto blocks allow you to pass a signal from one block to another without actually connecting them Each From block is associated with a Goto block The input to that Goto block is passed to the From block which then passes it tothe block connected toit To associate a Goto block with a F rom block enter the Goto block s tag in the Goto tag parameter A From block can receive its signal from only one Goto block although a Goto block can pass its signal to more than one From block This figure shows that using a Goto block and a From block is equivalent to connecting the blocks to which those blocks are connected In the model at the left Block1 passes a signal to Block2 That model is equivalent to the model at the right which connects Block1 to the Goto block passes that signal to the From block then on to Block2 gt A A Block1 Block2 Block1 Goto From Block2 Associated Goto and From blocks can appear anywhere in a model with this exception if either block is in a conditionally executed subsystem the other block must be either in the same subsystem or in a subsystem below it in the model hierarchy but not in another conditionally executed subsystem However if a Goto block is connected to a state port the signal can be sent to a From block inside another conditi
53. Cx Du define S_FUNCTION_NAME csfunc include simstruc h static double Al2 2 0 09 0 01 static double B 2 2 1 j l Fa 0 p ee N static double C 2 2 0 2 1 i 7D W riting S Functions as C M EX iles static double D 2 2 3 0 Fa ae y e mdllnitializeSizes initialize the sizes structure static void mdll nitializeSizes SimStruct S ssSetNumContStates S 2 number of continuous states ssSetNumDi scStates S 0 number of discrete states ssSetNuml nputs S 2 number of inputs ssSetNumOutputs S 2 number of outputs ssSetDirectFeedThrough S 1 direct feedthrough flag Matrix Dis nonempty ssSetNumSampleTimes S 1 number of sample times ssSetNumSFcnParams S 0 number of input arguments ssSetNumRWork S 0 number of real work vector elements ssSetNuml Work S 0 number of integer work vector elem s ssSetNumPWork S 0 number of pointer work vector elem s mdl I nitializeSampleTimes initialize sample times array static void mdll nitializeSampleTimes SimStruct S ssSetSampleTime S 0 CONTINUOUS SAMPLE_TI ME ssSetOffsetTime S 0 0 0 mdlInitializeConditions initialize the states static void mdlInitializeConditions double x0 SimStruct S int i for i 0 i lt 2 i X0 0 0 mdi Outputs compute the o
54. Final state name Limit output Maximum number of output rows to save Decimation factor Algebraic loop diagnostic Minimum step size diagnostic Unconnected input ports diagnostic Unconnected output ports diagnostic Unconnected lines diagnostic Consistency checking Intrinsic zero crossing detection see Zero Crossings on page 10 3 Close callback Pre load callback Post load callback Save callback Start simulation callback Stop simulation callback variable or vector xl niti al on off variable xFinal on off scalar 1000 scalar 1 none warning warning error none warning none warning none warning on off on of f command or variable command or variable command or variable command or variable command or variable command or variable error error error error These examples show how to set model parameters for the my model system This command sets the simulation start and stop times set_param mymodel StartTime 5 StopTime 100 A 5 A Model and Block Parameters This command sets the solver toode15s and changes the maximum order set_param mymodel Solver odel5s MaxOrder 3 This command associates aSavefcn callback set _param mymodel SaveFcn my_save_cb A 6 Common Block Parameters Common Block Parameters Table A 2 Common Block Parameters This table lists the parameters common to al
55. For example for num and den as defined above the icon looks like this z2 4 22 1422 e Todisplay a zero pole gain transfer function enter this command droots z p k For example the above command creates this icon for these values z p 1 1 k 1 4 s H1Xs 1 You can adda fourth argument z or z toexpressthe equation in terms of zor 1 z If the parameters are not defined or have no values when you create the icon Simulink displays three question marks in the icon When the parameter values are entered in the mask dialog box Simulink evaluates the transfer function and displays the resulting equation in the icon Controlling Icon Properties You can control a masked block s icon properties by selecting among the choices below the Drawing commands field The Icon Page Icon frame Theicon frameis the rectangle that encloses the block You can choose to show or hide the frame by setting the Icon frame parameter to Visible or Invisible The default is to make the icon frame visible For example this figure shows visible and invisible icon frames for an AND gate block Se D Visible Invisible Icon transparency Theicon can be set to Opaque or Transparent either hiding or showing what is underneath the icon Opaque the default covers information Simulink draws such as port labels This figure shows opaque and transparent icons for an AND gate block Notice the text on the transp
56. Generator Purpose Library Description oo00 9 132 oo gt Generate various waveforms Sources The Signal Generator block can produce one of three different waveforms sine wave square wave and sawtooth wave The signal parameters can be expressed in Hertz the default or radians per second This figure shows each signal displayed on a Scope using default parameter values EJ Scope Sine EJ Scope Square DAA A 2 DAA A 2 n nnn nn A Sd a a Sf J 1 I a i 1 n hf LETT fe CEL 5 0 4 0 Time offset 0 Time offset 0 Sine Wave Square Wave EJ Scope Sawtooth DAA A 2 0 Time offset 0 Sawtooth Wave A negative Amplitude parameter value causes a 180 degree phase shift Y ou can generate a phase shifted wave at other than 180 degrees in a variety of ways including inputting a Clock block signal toa MATLAB Fcn block and writing the equation for the particular wave Signal Generator Parameters and Dialog Box Characteristics You can vary the output settings of the Signal Generator block whilea simulation is in progress This is useful to determine quickly the response of a system to different types of inputs Signal Generator r Signal Generator pute somes wave fams The wave form a sine wave square wave or p Parameters sawtooth wave The default is a sine wave Wave form sine x Amplitude The signal amplitude The default is 1 1
57. Real Time Workshop enables you to implement your designs quickly without lengthy hand coding and debugging Control signal processing and dynamic system algorithms can be implemented by developing graphical Simulink block diagrams and automatically generating C code Embedded Real Time Control Once a system has been designed with Simulink code for real time controllers or digital signal processors can be generated cross compiled linked and downloaded onto your selected target processor The Real Time Workshop supports DSP boards embedded controllers and a wide variety of custom and commercially available hardware Real Time Simulation You can create and execute code for an entire system or specified subsystems for hardware in theloop simulations Typical applications include training simulators pilot in the loop real time model validation and testing Stand Alone Simulation Stand alone simulations can be run directly on your host machine or transferred to other systems for remote execution Because time histories are saved in MATLAB as binary or ASCII files they can be easily loaded into MATLAB for additional analysis or graphic display Key Features Real Time Workshop provides a comprehensive set of features and capabilities that provide the flexibility to address a broad range of applications e Automatic code generation handles continuous time discrete time and hybrid systems e Optimized code guarantees fast executi
58. Revert Help Sample Time N A Vectorized N A The Goto block tag whose visibility is defined by the location of this block 9 73 Ground Purpose Library Description Bi 9 74 Parameters and Dialog Box Characteristics Ground an unconnected input port Connections The Ground block can be used to connect blocks whose input ports are not connected to other blocks If you run a simulation with blocks having unconnected input ports Simulink issues warning messages Using Ground blocks to ground those blocks avoids warning messages The Ground block outputs a signal with zero value r Ground Used to ground input signals Prevents warnings about unconnected input ports Outputs zero Pf Help Sample Time Inherited from driven block Vectori zed Yes Hit Crossing Purpose Library Description Zt Parameters and Dialog Box Detect crossing point Nonlinear The Hit Crossing block detects when the input reaches the Hit crossing offset parameter value in the direction specified by the Hit crossing direction parameter This block locates transitions to from and through the offset The block finds the crossing point to within machine tolerance The block has one input If the Show output port check box is selected the block output indicates when the crossing occurs If the input signal is exactly the value of the offset value the block outputs a va
59. Running a Demo Model An interesting demo program provided with Simulink models the thermodynamics of a house To run this demo follow these steps 1 Start MATLAB See your MATLAB documentation if you re not sure how to do this 2 Run the demo model by typingt her mo in the MATLAB command window This command starts up Simulink and creates a model window that contains this model File Edit Simulation Format Tools blower heater cmd Set Point Fahrenheit to Celsius Heater Blower o Thermostat Celsius t Ina Indoor ws Fahrenheit M 50 nenne WS Outdoor Temp F2C Avg Outdoor Tin Temp Fahrenheit to Celsius Daily Temp Variation House Thermodynamics Double click Double click on the 7 for more info here for Simulink Help To start and stop the simulation use the Start Stop selection in the Simulation pull down menu When you open the model Simulink opens two Scope blocks labeled Indoor vs Outdoor Temp and Heat Cost 3 To start the simulation pull down the Simulation menu and choose the Start command As the simulation runs theindoor and outdoor temperatures appears in the Indoor vs Outdoor Temp Scope block and the cumulative heating cost appears in the Heat Cost Scope block 2 2 Running a Demo M odel 4 Tostop the simulation choose the Stop command from the Simulation menu If you want to explore other parts of the model loo
60. S Function User definable block Blocks may be written in M C or Fortran and must conform to S function standards t x u and flag are automatically passed to the S function by SIMULINK Extra parameters may be specified in the S function parameters field Parameters S function name mysfun S function parameter Apply Revert S Function1 dialog box S Function1 Function User definable block Blocks may be written in M C or Fortran and must conform to S function standards tx u and flag are automatically passed to the S function b SIMULINK Extra parameters may be specified ithe S function parameters field Parameters S function name mysfun S function parameters Apply Revert Help S function source file pe MYSFUN The follo define S_FU C MEX file or function sys mysfun M file switch flag M file This illustration shows the relationship between an S F unction block its dialog box and the source file that defines the block s behavior In this example the model contains two instances of an S F unction block Both blocks reference the same source file my sf un which can be either a C MEX file or an M file If both a C MEX file and an M file exist with the same name the C MEX file takes precedence and is the file that the S function uses You can use Simulink s masking facility
61. Simulation Parameters After you have set the simulation parameters and selected the solver you are ready toapply them to your model Press the Apply button on the bottom of the dialog box to apply the parameters to the model To apply the parameters and close the dialog box press the Close button Starting the Simulation After you have applied the solver and simulation parameters to your model you are ready torun thesimulation Select Start from the Simulation menu to run the simulation You can also use the keyboard shortcut CtrI T on a Microsoft Windows or X Windows system or T on a Macintosh When you select Start the menu item changes to Stop Running a Simulation Using Menu Commands Your computer beeps to signal the completion of the simulation NOTE A common mistake that new Simulink users make is to start a simulation while the Simulink block library is the active window Make sure your model window is the active window before starting a simulation To stop a simulation choose Stop from the Simulation menu The keyboard shortcut for stopping a simulation is Ctrl T on a Microsoft Windows or X Windows system or T ona Macintosh the same as for starting a simulation You can suspend a running simulation by choosing Pause from the Simulation menu When you select Pause the menu item changes to Continue Y ou proceed with a suspended simulation by choosing Continue If the model includes any blocks that write outp
62. Sys U end of mdi Derivatives VEEP md Update Handle discrete state updates sample time hits and maj or time step requirements VEEE function sys mdi Update t x u dperiod doffset next discrete state is output of the integrator Return next discrete state if we have a sample hit within a tolerance of le 8 If we don t have a sample hit return to indicate that the discrete state shouldn t change if abs round t doffset dperiod t doffset dperiod lt le 8 sys x 1 else sys This is not a sample hit so return an empty end matrix to indicate that the states have not changed end of mdi Update VECE mdi Out puts Return the output vector for the S function function sys mdl Outputs t x u doffset dperi od Return output of the unit delay if we have a sample hit within a tolerance of le 8 If we don t have a sample hit then return indicating that the output shouldn t change if abs round t doffset dperiod t doffset dperiod lt le 8 W riting S Functions as M Files sys x 2 else sys This is not a sample hit so return an empty end matrix to indicate that the output has not changed end of mdi Outputs Example Variable Step S Functions This M file is an example of an S function that uses a variable step time This example in an M file called vsf unc m calls md Get Ti meOf Next Var Hit when flag 4 Because the calcu
63. The Decimation parameter allows you to write data at every nth sample where n is the decimation factor The default decimation 1 writes data at every time step The Sample time parameter allows you to specify a sampling interval at which to collect points This parameter is useful when using a variable step solver where the interval between time steps may not be the same The default value of 1 causes the block to inherit the sample time from the driving block when determining which points to write During the simulation the block writes data to an internal buffer When the simulation is completed or paused that data is written to the workspace The block icon shows the name of the matrix to which the data is written Using Saved Data with a From File Block If the data written using a To Workspace block is to be saved and read later by a From File block the time must be added to the data and the matrix must be To Workspace transposed For moreinformation see the description of the From File block on page 9 66 Using Saved Data with a From Workspace Block If the data written using a To Workspace block is intended to be played back in another simulation using a From Workspace block the first column of the data must contain the simulation time values You can add a column with time values in two ways e By multiplexing the output of a Clock block as the first element of the vector input line of the To Workspace block
64. The default is 0 Apply Revert Help Characteristics SampleTime Continuous discrete or inherited Scalar Expansion Of parameters Vectorized Yes Zero Crossing No 9 135 Slider Gain Purpose Library Description E Dialog Box Characteristics 9 136 Vary a scalar gain using a slider Linear The Slider Gain block allows you to vary a scalar gain during a simulation using a slider The block accepts one input and generates one output J Slider Gain The lower limit of the slider range The kl u default is 0 ae The current slider value The default is 1 Help Close The upper limit of the slider range The default is 2 The edit fields indicate from left to right the lower limit the current value and the upper limit You can change the gain in two ways by manipulating the slider or by entering a new valuein the current value field You can changethe range of gain values by changing the lower and upper limits Close the dialog box by clicking on the Close button If you click on the slider s left or right arrow the current value changes by about 1 of the slider s range If you click on the rectangular area to either side of the slider s indicator the current value changes by about 10 of the slider s range To apply a vector gain to the block input consider using the Gain block described on page 9 70 To apply a matrix gain use the Matrix Gain block described on page 9 96
65. The values that appear in these fields are the values that will be used in the next simulation You can change the y axis settings by modifying the values in the Y max and Y min fields Change the x axis limits by entering a number or auto in the Time range field Entering a number of seconds causes each screen to display the amount of data that corresponds to that number of seconds Enter aut o to set the x axis to the duration of the simulation Apply the changes by clicking on the Apply or Close button Do not enter variable names in these fields Scope Characteristics Controlling Data Collection and Display You can control the amount of data that the Scope stores and displays by setting fields on the Settings tab Eg Properties Scope Ares Settings General Data history IV Limit rows to last 5000 I Save data to workspace I Floating scope To specify a decimation factor enter a number in the data field to the right of the Decimation choice To display data at a sampling interval select the Sample time choice and enter a number in the data field You can limit the number of points by checking the Limit points to last check box and entering a value in its data field You can automatically save the data collected by the Scope at the end of the simulation by checking the Save data to workspace check box and entering a variable namein the Variable name field The specified name must be unique amon
66. Time offset 0 The equation you modeled in this example can also be expressed as a transfer function The model uses the Transfer Fcn block which accepts u as input and outputs x So the block implements x u If you substitute sx for x in the equation above SX 2X U Solving for x gives X U S 2 Or x u 1 S 2 The Transfer Fcn block uses parameters to specify the numerator and denominator coefficients In this case the numerator is 1 and the denominator iss 2 Specify both terms as vectors of coefficients of successively decreasing Modeling Equations powers of s In this case the numerator is 1 or just 1 and the denominator is 1 2 Themodel now becomes quite simple ooono u 1 x oo ara s 2 Signal Transfer Fen Scope Generator The results of this simulation are identical to those of the previous model 3 37 3 Creating a M odel Saving a Model You can save a model by choosing either the Save or Save As command from the File menu Simulink saves the model by generating a specially formatted file called the moda file with the md extension that contains the block diagram and block properties The format of the model file is described in Appendix B If you are saving a model for the first time use the Save command to provide aname and location to the model file Model file names must start with a letter and can contain no more than 31 letters numbers and underscores If you a
67. a fixed step solver that performs no integration It is suitable for models having no states and for which zero crossing detection and error control are not important If you think your simulation may be providing unsatisfactory results see Improving Simulation Performance and Accuracy on page 4 19 Solver Options The default solver parameters provide accurate and efficient results for most problems In some cases however tuning the parameters can improve performance for more information about tuning these parameters see Improving Simulation Performance and Accuracy on page 4 19 You can tune the selected solver by changing parameter values on the Solver page Step Sizes For variable step solvers you can set the maximum and suggested initial step size parameters By default these parameters are automatically determined indicated by the valueauto For fixed step solvers you can set the fixed step size The default is alsoaut o Maximum step size The Max step size parameter controls the largest time step the solver can take The default is determined from the start and stop times h Estop J tsta rt max 50 Generally the default maximum step size is sufficient If you are concerned about the solver missing significant behavior change the parameter to prevent thesolver from taking toolargea step If the timespan of the simulation is very long the default step size may be too large for the solver to find th
68. a signal Library Nonlinear Description TheRateLimiter block limits the first derivative of the signal passing through it The output changes no faster than the specified limit The derivative is HA calculated using this equation rate HD yD t ti D u i and t i are the current block input and time and y i 1 and t i 1 arethe output and time at the previous step The output is determined by comparing rate to the Rising slew rate and Falling slew rate parameters e If rateis greater than the Rising slew rate parameter R the output is calculated as y i At R y i 1 e If rateis less than the Falling slew rate parameter F the output is calculated as y i At F y i 1 e If rateis between the bounds of Rand F the change in output is equal to the change in input yi u i Parameters Rate Limiter and Dialog ee er Limits rising and falling rates of input signal Box REISE The limit of the derivative of an increasing input Rising slew rate si gna l 1 Falling slew rate Apply Revert Help The limit of the derivative of a decreasing input signal 9 113 Rate Limiter Characteristics 9 114 Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving block Of input and parameters Yes No Relational Operator Purpose Library Description Perform the specified relational operation on the input Nonline
69. a simulation using menu commands e You can simulate M file and ME X file models as well as Simulink block diagram models e You can run a simulation from an M file allowing simulation and block parameters to be changed iteratively For moreinformation see Running a Simulation from the Command Line on page 4 21 4 3 4 Running a Simulation Running a Simulation Using Menu Commands This section discusses how to use Simulink menu commands and the Simulation Parameters dialog box to run a simulation Setting Simulation Parameters and Choosing the Solver You set the simulation parameters and select the solver by choosing Parameters from the Simulation menu Simulink displays the Simulation Parameters dialog box which uses three pages to manage simulation parameters e The Solver page allows you to set the start and stop times choose the solver and specify solver parameters and choose some output options e The Workspace I O page manages input from and output to the MATLAB workspace e The Diagnostics page allows you to select the level of warning messages displayed during a simulation Each page of the dialog box including the parameters you set on the page is discussed in detail in The Simulation Parameters Dialog Box on page 4 6 You can specify parameters as valid MATLAB expressions consisting of constants workspace variable names MATLAB functions and mathematical operators Applying the
70. already appears a sequence number is appended You can create a library from the command line using this command new_system newlib Library 3 13 3 Creating a M odel This command creates a new library named newl i b To display the library use theopen_system command These commands are described in Chapter 11 The library must be named Saved before you can copy blocks from it Modifying a Library When you open a library it is automatically locked and you cannot modify its contents To unlock the library select Unlock Library from the Edit menu Closing the library window locks the library Copying a Library Block into a Model When you copy a library block intoa model or another library Simulink creates a link tothelibrary block The reference block is a copy of the library block You can modify block parameters in the reference block but you cannot mask the block or if it is masked edit the mask Also you cannot set callback parameters for a reference block If you look under the mask of a reference block Simulink displays the underlying system for the library block Thelibrary and reference blocks arelinked by name that is the reference block is linked to the specific block and library whose names are in effect at the time the copy is made If Simulink is unable to find either the library block or the source library on your MATLAB path when it attempts to update the reference block the link becomes u
71. automatically renumbered to ensure that the Inport blocks are in sequence and that no numbers are omitted If you copy an Inport block into a system its port number is not renumbered unless its current number conflicts with an Inport block already in the system If the copied Inport block port number is not in sequence you must renumber the block or you will get an error message when you run the simulation or update the block diagram If the Inport block provides a vector signal you can specify the width of the input to the Inport block as the Port width parameter or let Simulink determine it automatically by providing a value of 1 the default The Sample time parameter is the rate at which the signal is coming into the system The default 1 causes the block to inherit its sample time from the block driving it It may be appropriate to set this parameter for Inport blocks in the top level system or in models where Inport blocks are driven by blocks whose sample time cannot be determined Inport Blocks in a Subsystem Inport blocks in a subsystem represent inputs to the subsystem A signal arriving at an input port on a Subsystem block flows out of the associated Inport block in that subsystem The Inport block associated with an input port on a Subsystem block is the block whose Port number parameter matches the relative position of the input port on the Subsystem block For example the Inport block whose Port number parameter is 1 get
72. by the discrete states ifany InitialState supersedes the initial states specified in the model The default an empty matrix causes the initial state values specified in the model to be used Initial Step positive scalar auto Suggested initial step size This property applies only to the variable step solvers The solvers try a step sizeof ni ti al Step first By default the solvers determine an initial step size automatically MaxOrder 1 2 3 4 5 Maximum order of ode15s This property applies only toodel5s Ma x Rows nonnegative integer 0 Limit number of output rows This property limits the number of rows returned int x andy tothelast MaxRows data logging time points If specified as 0 the default no limit is imposed MaxStep positive scalar auto Upper bound on the step size This property applies only to the variable step solvers and defaults to one fiftieth of the simulation interval 4 25 simset 4 26 Out put Points specified al Determine output points When set tospeci fied the solver produces outputs t x andy only at thetimes specified inti mespan When set toal t x andy also include the time steps taken by the solver OutputVariables txy tx ty xy t x y Se output variables If t x or y is missing from the property string the solver produces an empty matrix in the corresponding output t x ory Refine positive integer 1 Output refinefactor This property increases t
73. c 2 Clock matrix Mux To Workspace e By specifying time as a return value on the Simulation Parameters dialog box or from the command line described in Chapter 4 When the simulation is completed you can concatenate the time vector t to the matrix using a command like this matrix t matrix Examples In a simulation where the start time is 0 the Maximum number of rows is 100 the Decimation is 1 and the Sample time is 0 5 The To Workspace block collects a maximum of 100 points at time values of 0 0 5 1 0 1 5 seconds Specifying a Decimation of 1 directs the block to write data at each step In a similar example the Maximum number of rows is 100 and the Sample time is 0 5 but the Decimation is 5 In this example the block collects up to 100 points at time values of 0 2 5 5 0 7 5 seconds Specifying a Decimation of 5 directs the block to write data at every fifth sample The sample time ensures that data is written at these points In another example all parameters are as defined in the first example except that the Maximum number of rows is 3 In this case only the last three rows collected are written to the workspace If the simulation stop time is 100 data corresponds to times 99 0 99 5 and 100 0 seconds three points 9 149 To Workspace 9 150 Parameters and Dialog Box Characteristics To Workspace r To Workspace Writes input to specified matrix in MATLAB s main wo
74. code Embedded Real Time Control Once a system has been designed with Simulink code for real time controllers can be generated cross compiled linked and downloaded onto your selected target processor The RTW Ada Extension generates Ada code which can be run on a wide variety of custom and commercially available hardware Real Time Simulation You can create and execute code for an entire system or specified subsystems for hardware in the loop simulations Typical applications include training simulators pilot in the loop real time model validation and testing Stand Alone Simulation Stand alone simulations can be run directly on your host machine or transferred to other systems for remote execution Because time histories are saved in MATLAB as binary or ASCII files they can be easily loaded into MATLAB for additional analysis or graphic display Key Features RTW Ada Extension provides a comprehensive set of features and capabilities that provide the flexibility to address a broad range of applications Automatic code generation handles continuous time discrete time and hybrid systems Optimized code guarantees fast execution Control framework API uses customizable makefiles to build and download object files to target hardware automatically The Real Time W orkshop Ada Extension e Portable code facilitates usage in a wide variety of environments e Concise readable and well commented code provides ease of mai
75. condition parameter or the input States Inherited from driving block or parameters Vectorized Yes Zero Crossing No 9 159 Variable Transport Delay Purpose Library Description pN 9 160 Delay the input by a variable amount of time Nonlinear The Variable Transport Delay block can be used to simulate a variable time delay The block might be used to model a system with a pipe where the speed of a motor pumping fluid in the pipe is variable The block accepts two inputs the first input is the signal that passes through the block the second input is the time delay as show in this icon SSE Oy oua Variable Transport Delay The Maximum delay parameter defines the largest value the time delay input can have The block clips values of the delay that exceed this value The Maximum delay must be greater than or equal to zero If the time delay becomes negative the block clips it to zero and issues a warning message During the simulation the block stores time and input value pairs in an internal buffer At the start of the simulation the block outputs the Initial input parameter until the simulation time exceeds the time delay input Then at each simulation step the block outputs the signal at the time that corresponds to the current simulation time minus the delay time When output is required at a time that does not correspond to the times of the stored input values the block interpolates linearly between points I
76. create a subsystem by selecting existing blocks if more than one Outport block is included in the grouped blocks Simulink automatically renumbers the ports on the blocks The Outport block name appears in the Subsystem block icon as a port label To suppress display of the label select the Outport block and choose Hide Name from the Format menu 9 103 Outport 9 104 Outport Blocks in a Conditionally Executed Subsystem When an Outport block is in a triggered and or enabled subsystem you can specify what happens to its output when the subsystem is disabled it can be reset to an initial value or held at its most recent value The Output when disabled popup menu provides these options The Initial output parameter is the value of the output before the subsystem executes and if the reset option is chosen while the subsystem is disabled Outport Blocks in a Top Level System Outport blocks in a top level system have two uses to supply external outputs to the workspace which you can do by using either the Simulation Parameters dialog box or thes i m command and to provide a means for analysis functions to obtain output from the system e Tosupply external outputs to the workspace using the Simulation Parameters dialog box On the Workspace I O tab select the Output check box in the Save to workspace area and specify the variable in the data field EJ Simulation parameters untitled BEI Salver Workspace 10 Diagnos
77. discrete states or tasks to complete at termination Example Discrete State S Function Simulink includes afunction calledds func c which is an example of a discrete state system modeled in an S function Here is the code for the C language S function DSFUNC An example C file S function for defining a discrete system define S_F inc stat stati stati stati mdll nit static void ude ic do do do do ssSet ssSet ssSet ssSet ssSet ssSet ssSet ssSet Xx U me ub ub ub ub a um um um um Dir um um n l Ax n Bu n n Cx n Du n NCTI ON NAME dsfunc mstruc h e A 2 2 1 3839 0 5097 1 0 H e B 2 2 2 5559 0 p 0 4 2382 H e cl2 2 0 2 0761 0 71 7891 ie e D 2 2 0 8141 2 9334 1 2426 0 H izeSizes initialize the sizes structure mdl nitializeSizes SimStruct 5 ContStates S 0 number of continuous states DiscStates S 2 number of discrete states Inputs S 2 number of inputs Out puts S 2 number of outputs ectFeedThrough SFcnParams S 0 um RWor k S 0 S SampleTi mes S 1 number Pig x direct feedthrough flag Matrix D is nonempty number number of of real of sample times input work vector arguments el ements 8 35 8 S Functions ssSetNu
78. e B must be an n by m matrix where mis the number of inputs e C must bean r by n matrix where r is the number of outputs e D must bean r by m matrix n m ny A B rE C D The block accepts one input and generates one output The input vector width is determined by the number of columns in the B and D matrices The output vector width is determined by the number of rows in the C and D matrices Simulink converts a matrix containing zeros to a sparse matrix for efficient multiplication Discrete State Space Parameters and Dialog Box Characteristics Discrete State Space r Discrete State Space Discrete state space model n 1 Axin Buln yin Cain Dufn Parameters E x Initial conditions 0 Sample time 1 Apply Revert Help The matrix coefficients as defined in the above equations The initial state vector The default is 0 The time interval between samples Direct Feedthrough Sample Time Scalar Expansion States Vectorized Zero Crossing Only if D 0 Discrete Of the initial conditions Determined by the size of A Yes No Discrete Time Integrator Purpose Library Description Perform discrete time integration of a signal Discrete The Discrete Time Integrator block can be used in place of the Integrator block when constructing a purely discrete system The Discrete Time Integrator block allows you to e Define i
79. element ssSetCallSystemOutput S 2 call on 3rd element 2 Execute the subsystem in the appropriate md Out puts mdi Updates or md Derivatives routine For example static void md Outputs if int u 0 2 1 ssCall System S 0 else ssCall System S 2 W riting S Functions as C MEX Files sfun_fcncall c illustrates an S function configured to execute function call subsystems Function call subsystems are generally used by Stateflow blocks For more information on their use see the Stateflow documentation Instantaneous Update of S Function Inputs You can get instantaneous updates of S function inputs by accessing the inputs through pointers This is required for execution of function call subsystems whose inputs feed back into your S function To configure your S function to use input pointers set in mdi I nitializeSizes ssSetOptions S SS OPTION USING ssGet UPtrs Then in all the routines where you access the input include UPtrsType uPtrs ssGetUPtrs S Thei th input is then tuPtrs i Exception Handling Each time an S function is invoked Simulink performs overhead tasks associated with exception handling If the S function does not contain any routines that can generate exceptions you can improve the performance of the simulation If you are not using routines that can throw an exception set this option in mdi nitializeSizes ssSetOption S SS_OPTION EXCEPTION _F
80. enclosed in brackets and scoped tag names are enclosed in braces The Goto block identifier This parameter p Parameters identifies the Goto block whose scope is defined in Tes this block The scope of the Goto block tag local scoped or global The default is local Apply Revert Help Characteristics Sample Time Inherited from driving block Vectorized Yes 9 72 Goto Tag Visibility Purpose Library Description 1 Parameters and Dialog Box Characteristics Define scope of Goto block tag Connections The Goto Tag Visibility block defines the accessibility of Goto block tags that have scoped visibility The tag specified as the Goto tag parameter is accessi ble by F rom blocks in the same subsystem that contains the Goto Tag Visibility block and in subsystems below it in the model hierarchy A Goto Tag Visibility block is required for Goto blocks whose Tag visibility parameter value is scoped It is not used if the tag visibility is either local or global The block icon shows the tag name enclosed in braces Goto Tag Visibility r GotoT aaVisibility Used in conjunction with Goto and From blocks to define the visibility of scoped tags For example if this block resides in a subsystem or root system called MYSYS then the tag is visible to From blocks that reside in MYSYS or in subsystems of MYSYS Parameters Goto tag A Apply
81. follow these steps 1 Select the line Gain Sum 2 Position the pointer on the line where you want the vertex Gain t Sum 3 While holding down the Shift key press and hold down the mouse button The cursor shape changes to a circle that encloses the new vertex Gain Sum 4 Drag the pointer to the desired location A DANG Gain Sum 5 Release the mouse button and the Shift key N Gain Sum Lines Moving a Line Vertex To move a vertex of a line follow these steps 1 Position the pointer on the vertex then press and hold down the mouse button The cursor changes to a circle that encloses the vertex Constant Scope 2 Drag the pointer to the desired location Constant or Scope 3 Release the mouse button Constant z Scope Displaying Line Widths You can display the widths of all lines in a model by turning on Line Widths from the Format menu Simulink indicates the width of each signal at the block that originates the signal and the block that receives it When you start a simulation or update the diagram and Simulink detects a mismatch of input and output ports it displays an error message and shows line widths in the model 3 21 3 Creating a M odel Signal Labels 3 22 You can label signals toannotate your model Labels can appear above or bel ow horizontal lines or line segments and left or right of vertical lines or line segments Labels can appear at either end at
82. from negative to positive velocity is extremely sharp that is there is no rounding of corners at the discontinuity To see a bouncing ball demo type bounce at the MATLAB prompt Integration of Discontinuous Signals Numerical integration routines are formulated on the assumption that the signals they areintegrating are continuous and have continuous derivatives If a discontinuity state event is encountered during an integration step Simulink uses zero crossing detection to find the time at which the discontinuity occurs An integration step is then taken up tothe left edge of the discontinuity Finally Simulink steps over the discontinuity and begins a new integration step on the next piece wise continuous portion of the signal 10 3 10 Additional Topics 10 4 Implementation Details An example of a Simulink block that uses zero crossings is the Saturation block Zero crossings detect these state events in the Saturation block e Theinput signal reaches the upper limit e Theinput signal leaves the upper limit e Theinput signal reaches the lower limit e Theinput signal leaves the lower limit Simulink blocks that define their own state events are considered to have intrinsic zero crossings If you need explicit notification of a zero crossing event use the Hit Crossing block See page 10 5 for a list of blocks that incorporate zero crossings The detection of a state event depends on the construction of an internal zero c
83. if FALSE The block icon shows the selected operator e For two or more inputs the block performs the operation between all of the inputs If the inputs are vectors the operation is performed between corresponding elements of the vectors to produce a vector output For a single vector input the block applies the operation except the NOT operator to all elements of that vector The NOT operator accepts only one input which can bea scalar or vector If the input is a vector the output is a vector of the same size containing the logical complements of the elements of the input vector When configured as a multi input XOR gate this block performs an addition modulo two operation as mandated by the IEEE Standard for Logic Elements Logical Operator r Logical Operator Logical operators For a single input operators are applied across the input vector For multiple inputs operators are applied across the inputs The logical operator to be applied to the block inputs Valid choices are the operators listed above r Parameters Operator AND Number of input ports Apply Revert Help The number of block inputs The value must be appropriate for the selected operator 9 85 Logical Operator 9 86 Characteristics Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving block Of inputs Yes No Look Up Table Purpose
84. maintain its most recent value e Choose reset to cause the output to revert to its initial condition Set the Initial output to the initial value of the output r Outport Provides an output port for a sybsystem or model When a subsystem is disabled the output is either held at its last value or set to the Initial output Parameters Port number Output when disabled held held R i Select an option to set the Outport output while the ae 7 subsystem is disabled The initial condition and the value when reset Apply Revert Help Setting States When the Subsystem Becomes Re ena bled When an enabled subsystem executes you can choose whether to hold the subsystem states at their previous values or reset them to their initial conditions Enabled Subsystems Todothis open the Enable block dialog box and select one of the choices for the States when enabling parameter as shown in the dialog box below e Choose held to cause the states to maintain their most recent values e Choose reset to cause the states to revert to their initial conditions Enable r Enable Port Place this block in a subsystem to create an enabled subsystem States when enabling held i Select an option to set the states when the subsystem is re enabled Parameters T Show output port reset Apply Revert Help Close O utputting the Enable Control Signal An option on the E nable
85. me A B C D Initial conditions Sample time Discrete Transfer Fcn DiscreteTransferFcn Numerator Denomi nator Sampl eTi me Numerator Denominator Sample time Discrete Zero Pole Di screteZeroPole Zeros Zeros internal external scalar or vector 0 off on scalar or vector inf scalar or vector i nf off on off on scalar Sample period 1 or vector period offset matrix 1 matrix 1 matrix 1 matrix 1 vector 0 scalar Sample period 1 or vector period offset vector 1 vector 1 0 5 scalar sample period 1 or vector period offset vector 1 A 13 A Model and Block Parameters Table A 4 Discrete Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Poles Poles vector 0 0 5 Gain Gain scalar 1 Sampl eTi me Sample time scalar sample period 1 or vector period offset First Order Hold First Order Hold masked Unit Delay Unit Del ay X0 Initial condition scalar or vector 0 Sampl eTi me Sample time scalar sample period 1 or vector period offset Zero Order Hold ZeroOrderHold Sampl eTi me Sample time scalar sample period 1 or vector period offset Table A 5 Linear Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Derivative Deri vat i ve no block specific parameters Dot Product Dot Product masked Gain
86. models 3 33 Apply button on Mask Editor 6 9 Assignment mask parameter 6 10 Autoscale icon drawing coordinates 6 22 auto scaling Scope axes 9 123 B Backlash block 9 12 zero crossings 10 5 backpropagating sample time 10 15 Backspace key 3 8 3 22 3 24 Backward Euler method 9 43 Backward Rectangular method 9 43 bad link 3 14 Band Limited White Noise block 9 16 9 111 9 158 simulation speed 4 20 bdcl ose command 11 6 bdroot command 11 7 bitmap printing to 3 41 block descriptions creating 6 6 entering 6 24 block diagrams printing 3 39 block dialog boxes closing 11 8 opening 2 9 3 7 11 19 block icons creating for masked blocks 6 17 drawing coordinates 6 22 font 3 10 graphics on 6 18 icon frame property 6 21 icon rotation property 6 21 icon transparency property 6 21 properties 6 20 question marks in 6 19 6 20 text on 6 17 l 1 Index transfer functions on 6 19 block libraries 3 13 Blocksets and Toolboxes 9 3 block type of masked block 6 24 BlockDefaults section of md file B 3 blocks 3 6 3 12 1 2 Connections 9 7 Demos 9 3 Discrete 9 4 Extras 9 3 Linear 9 5 Nonlinear 9 6 Sinks 9 4 Sources 2 7 9 3 block names changing location 3 10 copied blocks 3 6 editing 3 9 flipping location 3 10 font 3 10 hiding and showing 3 10 location 3 9 newline character in 11 3 rules 3 9 sequence numbers 3 6 3 7 slash character in 11 3 block parameters A 7 A 10 A 22 changing during simulatio
87. mul i nk src below the MATLAB root directory NOTE Werecommend that you use the C MEX file template when developing MEX S functions Statements Required at the Top of the File The MEX file must contain a statement that includes the definition of the SimStruct data structure that stores pointers to the data used by the simulation The included code also defines the macros used to store and retrieve data in theSi mStr uct described in detail in Appendix C This statement must precede the function definitions include simstruc h Definethe name of your S function with a statement likethe one below substituting your model name for your_sfunction_name_here define S_FUNCTION_NAME your_sfunction_name_here Statements Required at the Bottom of the File Include this code at the end of your C MEX file S function ifdef MATLAB_MEX_FILE x ls this being compiled as MEX file include si mulink c MEX file interface mechanism else include cg_sfun h Code generation registration func endi f 8 27 8 S Functions 8 28 These statements select the appropriate code for your particular application e simulink c is included if the file is being compiled into a MEX file e cg_sfun h is included if the file is being used in conjunction with the Simulink Real Time Workshop to produce a stand alone or real time executable Defining S Function Block Characteristics Thesi zes structurein theSi mStr
88. needed routines only on sample hits Here is the code for the M file S function function sys x0 str ts dsfunc t An example X n 1 y n Generate a x u flag M file S function for defining a discrete system This S function implements discrete equations in this form Ax n Bu n Cx n Du n discrete linear system A 1 3839 0 5097 1 0000 01 B 2 5559 0 0 4 2382 C 0 2 0761 0 7 7891 D 0 8141 2 9334 1 2426 0 switch flag case 0 sys mdlInitializeSizes A B C D Initialization case 2 sys mdl Update t x u A B C D Update discrete states case 3 sys mdl Outputs t x u A B C D Calculate outputs case l 4 9 Unused flags sys otherwise error unhandled flag numstr flag Error handling 8 18 W riting S Functions as M Files end end of dsfunc function sys x0 str ts mdll nitializeSizes A B C D call simsizes for a sizes structure fill it in and convert it to a sizes array sizes simsizes sizes NumContStates 0 sizes NumDiscStates 2 sizes NumOut puts 2 sizes Numi nputs 2 sizes DirFeedthrough 1 Matrix D is non empty sizes NumSampleTi mes 1 sys simsizes sizes x0 ones 2 1 Initialize the discrete states str Set str to an empty matrix ts 1 0 sample time period offset end of mdllnitializeSizes function sys mdl Updates t x u A B C D Sys
89. occurrence of the label hold down the Shift key while you select the label then press the Delete or Backspace key Signal Labels To change the font of a signal label select the signal choose Font from the Format menu then select a font from the Set Font dialog box Signal Label Propagation Signal label propagation is the automatic labeling of a line emitting from a connection block The Connections library blocks that support signal label propagation are the Demux Enable From Inport Mux Selector and Subsystem blocks The labeled signal must be on a line feeding a connecting block and the propagated signal must be on a line coming from the same connecting block or one associated with it Topropagatea signal label create a signal label starting with the lt character on the output of one of the listed connection blocks When you run the simulation or update the diagram the actual signal label appears enclosed within angle brackets The actual signal label is obtained by tracing back through the connection blocks until a signal label is encountered This example shows a mode with a signal label and the propagated label both before and after updating the block diagram In the first figure the signal entering the Goto block is labeled abe and the signal leaving the associated From block is labeled with a single lt The second figure shows the same model after choosing Update Diagram from the Edit menu Ghee BTL
90. of Inport blocks in the subsystem Similarly the number of output ports drawn on the block corresponds to the number of Outport blocks in the subsystem If Inport and Outport block names are not hidden they appear as port labels on the Subsystem block For more information about subsystems see Creating Subsystems in Chapter 3 None Sample Time Depends on the blocks in the subsystem Vectorized Depends on the blocks in the subsystem Zero Crossing Yes for enable and trigger ports if present 9 141 Sum Purpose Generate the sum of inputs Library Linear Description The Sum block adds scalar and or vector inputs or elements of a single vector input depending on the number of block inputs e f the block has more than one input the block output is an element by element sum across the inputs If all inputs are scalars the output is a scalar For a block having n inputs if any input is a vector each element of the output is generated as H y ul u2 un This model represents using the Sum block in this way The broken lines indicate that each signal can bea scalar or vector The output is a scalar only if all inputs are scalars L gt gt If the block has one vector input the block output is the scalar sum of the elements of the input y Ly This model represents using the Sum block in this way The solid line input signal indicates that the input is a vector gt
91. or more information see Error Tolerances on page 4 11 Caveat It is possible to create models that exhibit high frequency fluctuations about a discontinuity chattering Such systems typically arenot physically realizable a mass less spring for example Because chattering causes repeated detection of zero crossings the step sizes of the simulation become very small essentially halting the simulation If you suspect that this behavior applies to your model you can disable zero crossings by selecting the Disable zero crossing detection check box on the Diagnostics page of the Simulation Parameters dialog box Although disabling zero crossing detection may alleviate the symptoms of this problem you no longer benefit from the increased accuracy that zero crossing detection provides A better solution is to try to identify the source of the underlying problem in the model These blocks incorporate zero crossings Table 10 1 Blocks With Intrinsic Zero Crossings Block Description of Zero Crossing Abs One to detect when the input signal crosses zero in either the rising or falling direction Backlash Two one to detect when the upper threshold is engaged and one to detect when the lower threshold is engaged 10 5 10 Additional Topics 10 6 Table 10 1 Blocks With Intrinsic Zero Crossings Continued Block Description of Zero Crossing Dead Zone Two one to detect when the dead zone is entered the
92. parameters and starting the simulation with the Start command described in detail in Chapter 4 e You can encapsulate complex groups of related blocks in a single block called a subsystem Creating subsystems is described in detail in Chapter 3 e You can create a customized icon and design a dialog box for a block by using the masking feature described in detail in Chapter 6 In thet her mo model Running a Demo M odel all Subsystem blocks have customized icons created usingthe masking feature e Scope blocks display graphic output much as an actual oscilloscope does A Scope block displays its input signal Scope blocks are described in detail in Chapter 9 Other Useful Demos Other demos illustrate useful modeling concepts You can access these demos from the Simulink block library window 1 Typesi mulink inthe MATLAB command window The Simulink block library window appears Library simulink Oo x Eile Edit Simulation Format Tools rial wy ns sa BS eS ET PS ft Sources Sinks Discrete Linear Nonlinear Connections Blocksets amp Simulink Block Library Demos Toolboxes Copyright c 1990 97 by The MathWorks Inc 2 Doubleclick on the Demos icon The MATLAB Demos window appears This window contains several interesting sample models that illustrate useful Simulink features the Demos icon 2 Q uick Start Building a Simple Model 2 6 This example shows y
93. ssSetNumContStates S 1 number of continuous states ssSetNumDiscStates S 1 number of discrete states ssSetNuml nputs S 1 number of inputs ssSetNumOut puts S 1 number of outputs ssSetDirectFeedThrough S 0 direct feedthrough flag ssSetNumSampl eTi mes S 2 number of sample times ssSetNumSFcnParams S 0 number of input arguments ssSetNumRWork S 0 number of real work vector elem s ssSetNuml Work S 0 number of integer work vector elems ssSetNumPWork S 0 number of pointer work vector elems mdi I nitializeSampleTimes initialize sample times array static void mdll nitializeSampleTimes SimStruct S ssSetSampleTime S 0 CONTINUOUS SAMPLE TI ME ssSetOffsetTime S 0 0 0 1 1 ssSetSampleTime S 1 1 0 ssSetOffsetTime S 1 0 0 mdllnitializeConditions initialize the states static void mdlInitializeConditions double x0 SimStruct S int i for i 0 i lt 2 i X0 0 0 8 38 W riting S Functions as C M EX iles mdi Outputs compute the outputs static void md Outputs double y const double x const double u SimStruct S int tid if sslsSamplehHit 1 tid y 0 x 1 The discrete output of the S function mdi Update perform action at major integration time step static void mdl Update double x const double u SimStruct S int tid if
94. sslsSamplehHit 1 tid x 1 x 0 The discrete state of the S function mdli Derivatives compute the derivatives static void mdi Derivatives double dx const double xx const double u SimStruct S int tid dx 0 u 0 mdi Terminate called when the simulation is terminated static void mdlTerminate SimStruct S i ifdef MATLAB MEX_FILE ls this being compiled as MEX file include si mulink c MEX file interface mechanism else include cg_sfun h Code generation registration func endi f 8 39 8 S Functions Since there are notasks to complete at termination md Ter mi nat e isan empty function md Deri vati ves calculates the derivatives of the continuous states of the state vector x and md Update contains the equations used to update the discrete states of x Example Variable Step S Functions This example is of an S function that uses a variable step time Variable step size functions require a call tomd Get Ti meOf Next Var Hit whichis an S function routine that calculates the time of the next sample hit The S function isin an C program called vsf unc c located in your Simulink directory vsf unc is a discrete S function that delays its first input by an amount of time determined by the second input Here is the C code for vsfunc c vsfunc Variable step S function example This block implements a variable step delay in which the f
95. system and block parameter values get_param obj parameter get_param objects parameter get _param obj parameter where obj is asystem or block path name returns the value of the specified parameter Case is ignored for parameter names get_param objects parameter accepts a cell array of full path specifiers enabling you to get the values of a parameter common to all objects specified in the cell array Appendix A contains lists of model and block parameters This command returns the value of the Gain parameter for the Inertia block in theRequisite Friction Subsystem of thec utch system get_param clutch Requisite Friction Inertia Gain ans l Iv le These commands display the block types of all blocks in the mx b system the current system described in A Sample Masked Subsystem on page 6 3 gt gt blks find system gcs Type block gt gt listbl ks get_param blks BlockType listblks SubSystem Inport Constant Gai n Sum Outport find system set param 11 17 new_system Purpose Syntax Description Example See Also 11 18 Create a new empty Simulink system new_system sys new system sys creates a new empty system with the specified name If sys Specifies a path the new system will be a subsystem of the system specified in the path new_ system does not open the system window For a list of
96. the Assignment type is Evaluate the string gai n is evaluated by MATLAB and the result is assigned to the variable If the type is Literal the string is not evaluated by MATLAB so the variable contains thestring gain If you need both the string entered as well as the evaluated value choose Literal Then usethe MATLAB eval command in theinitialization commands For example ifLit Val isthestring gai n then to obtain the evaluated value use the command value eval LitVal In general most parameters use an Assignment type of Evaluate Creating the First Prompt Tocreatethe first prompt in thelist enter the prompt in the Prompt field the variable that is to contain the parameter value in the Variable field and choose a control style and an assignment type Inserting a Prompt Toinsert a prompt in the list 1 Select the prompt that appears immediately be ow where you want to insert the new prompt and click on the Add button to the left of the prompt list 2 Enter thetext for the prompt in the Prompt field Enter the variable that is to hold the parameter value in the Variable field Editing a Prompt To edit an existing prompt 1 Select the prompt in the list The prompt variable name control style and assignment type appear in the fields below the list 2 Edit the appropriate value When you click the mouse outside the field or press the Enter or Return key Simulink updates the prompt Deleting a Prompt To del
97. the default parameter values for the new system see Appendix A This command creates a new system named mysys new_system mysys This command creates a new subsystem named mysys in thevdp system new_system vdp mysys close system open_system save system open_system Purpose Syntax Description Example See Also Open a Simulink system window or a block dialog box open_system sys open_system bl k open_system blk force open_system sys Opens the specified system or subsystem window open_system bl k where bik isa full block path name opens the dialog box associated with the specified block If the block s OpenFcn callback parameter is defined the routine is evaluated open_system blk force where bik isa full path name or a masked system looks under the mask of the specified system This command is equivalent to using the Look Under Mask menu item This command opens the control er system in its default screen location open_system controller This command opens the block dialog box for the Gain block in thecont roller system open_system controller Gain close system new_system Save_system 11 19 replace_block Purpose Syntax Description Example See Also 11 20 Replace blocks in a Simulink model replace _block sys blk1l blk2 noprompt replace _block sys Parameter value blk
98. thecenter or in any combination of these locations Using Signal Labels To create a signal label double click on the line segment and type the label at the insertion point When you click on another part of the model the label fixes its location NOTE When you create a signal label take care to double click on the line If you click in an unoccupied area close to the line you will create a model annotation instead To move a signal label drag the label to a new location on the line When you release the mouse button the label fixes its position near the line Tocopy a signal label hold down the Ctrl key you can also use the Option key on a Macintosh while dragging the label to another location on the line When you release the mouse button the label appears in the original and new location To edit a signal label select it e Toreplace the label on a Microsoft Windows or X Windows system click on the label then double click or drag the cursor to select the entire label Then enter the new label On a Macintosh select the label and enter the new text e Toinsert characters click between two characters to position the insertion point then insert text e Toreplace characters drag the mouse to select a range of text to replace then enter the new text Todelete all occurrences of a signal label delete all the characters in the label When you click outside the label the labels are deleted To delete a single
99. this port either directly or through a series of blocks with direct feedthrough an algebraic loop results To resolve this loop feed the block state into the reset port instead To access the block s state select the Show state port check box Specifying the Absolute Tolerance for the Block State When your model contains states having vastly different magnitudes defining the absolute tolerance for the model might not provide sufficient error control Todefine the absolute tolerance for an Integrator block s state provide a value for the Absolute tolerance parameter If the block has more than one state the same value is applied to all states For moreinformation about error control see Error Tolerances on page 4 11 Choosing All Options When all options are selected the icon looks like this Initial condition Integrator 9 83 Integrator Parameters and Dialog Box Characteristics 9 84 Integrator r Integrator Continuous time integration of the input signal m Parameters Extemal reset Initial condition source internal Initial condition 0 T Limit output Upper saturation limit inf Lower saturation limit inf I Show saturation port I Show state port Absolute tolerance auto Apply Revert Resets the states to their initial conditions when a trigger event rising falling or either occurs in the reset signal Gets th
100. to the times of the stored input values the block interpolates linearly between points When the delay is smaller than the step size the block extrapolates from the last output point which may produce inaccurate results Because the block does not have direct feedthrough it cannot usethe current input to calculateits output value Toillustrate this point consider a fixed step simulation with a step size of 1 and the current time at t 5 If the delay is 0 5 the block needs to generate a point at t 4 5 Because the most recent stored time valueis at t 4 the block performs forward extrapolation The Transport Delay block does not interpolate discrete signals Instead it returns the discrete value at t tdday This block differs from the U nit Delay block which delays and holds the output on sample hits only Using i nmod tolinearize a model that contains a Transport Delay block can be troublesome For more information about ways to avoid the problem see Linearization in Chapter 5 9 153 Transport Delay Parameters Transport Delay H r Transport Delay a nd Dia log Applies specified delay to the input signal Best accuracy Box ee ee ere ee The amount of simulation time that the input signal is delayed before propagating it to the Parameters output The value must be nonnegative Time delay 1 Eem The output generated by the block between the a start of the simulation and the Time delay Initial buf
101. truth table for modeling programmable logic arrays PLAs logic circuits decision tables and other Boolean expressions You can use this block in conjunction with Memory blocks to implement finite state machines or flip flops You specify a matrix that defines all possible block outputs as the Truth table parameter Each row of the matrix contains the output for a different combination of input elements You must specify outputs for every combination of inputs Each output can be any numerical value it is not constrained to the values of 0 and 1 The number of columns is the number of block outputs The relationship between the number of inputs and the number of rows is number of rows 2 number of inputs Simulink returns a row of the matrix by computing the row s index from the input vector elements Simulink computes the index by building a binary number where input vector elements having zero values are 0 and elements having nonzero values are 1 then adds 1 to the result For an input vector u of m elements row index 1 u m 2 u m1 2 u 1 2 1 Example of Two Input AND Function This example builds a two input AND function which returns 1 when both input elements are 1 and 0 otherwise To implement this function specify the Truth table parameter value as 0 0 0 1 The portion of the model that provides theinputs to and the output from the Combinatorial Logic block might look like this Input 1 Inp
102. window Save a Simulink system Find a Simulink system or block Add a new block to a system Delete a block from a system Replace a block in a system Add a line to a system Delete a line from a system Get a parameter value Set parameter values Get the path ofthe current block Get the path of the current system Get the name of the root level system Open the Simulink block library new_system open_system close system bdclose Save system find system add_bl ock delete block replace block add_line delete line get param set param gcb gcs bdroot si mul i nk Introduction How to Specify Parameters for the Commands The commands described in this chapter require that you specify arguments that describe a system block or block parameter Appendix A provides comprehensive tables of model and block parameters How to Specify a Path for a Simulink Object Many of the commands described in this chapter require that you identify a Simulink system or block Identify systems and blocks by specifying their paths e To identify a system specify its name which is the name of the file that contains the system description without the md extension system e Toidentify a subsystem specify the system and the hierarchy of subsystems in which the subsystem resides system subsystemz subsystem e Toidentify a block specify the path of the system that contains the block and specify the block name system subsystemz
103. you suspect that a problem is stiff or if ode45 failed or was very inefficient try odel5s ode23s is based on a modified Rosenbrock formula of order 2 Because it isa one step solver it may be more efficient than ode15s at crude tolerances It can solve some kinds of stiff problems for which ode15s is not effective e discrete variable step is the solver Simulink chooses when it detects that your model has no continuous states NOTE For astiff problem solutions can change on a time scale that is very short compared to the interval of integration but the solution of interest changes on a much longer time scale Methods not designed for stiff problems are ineffective on intervals where the solution changes slowly because they use time steps small enough to resolve the fastest possible change J acobian matrices are generated numerically for ode15s andode23s For more information see Shampine L F Numerical Solution of Ordinary Differential Equations Chapman amp Hall 1994 Fixed step solvers You can choose these fixed step solvers ode5 ode4 ode3 ode2 odel anddiscrete e ode5 is the fixed step version of ode45 the Dormand Prince formula e ode4 is RK4 the fourth order Runge Kutta formula 4 9 4 Running a Simulation 4 10 ode3 is the fixed step version ofode23 the Bogacki Shampine formula ode2 is Heun s method also known as the improved Euler formula odel is Euler s method discrete fixed step is
104. 1 at 0 375 seconds and returns to 0 at 0 875 seconds m Enable 1 block C Ts 0 125 Number T205 Subsystem T a 7 6 Enabled Subsystems The chart below indicates when the discrete blocks execute Signal E Block D Block C Block B Block A Blocks A and B execute independent of the enable signal because they are not part of the enabled subsystem When the enable signal becomes positive blocks C and D execute at their assigned samplerates until the enable signal becomes 0 125 25 375 50 625 75 875 1 0 Time sec A start of execution for a block zero again Note that block C does not execute at 0 875 seconds when the enable signal changes to zero 7 Conditionally Executed Subsystems Triggered Subsystems Triggered subsystems are subsystems that execute each time a trigger event occurs A triggered subsystem has a single control input called the trigger input which determines whether the subsystem executes You can choose from three types of trigger events to force a triggered subsystem to begin execution e Arising trigger where the control signal or any element of a vector control signal changes from 0 to a positive value e A falling trigger where the control signal or any element of a vector control signal changes from 0 to a negative value e Either arising or a falling trigger where the control signal
105. 1 at each time step The maximum step size is too small If you changed the maximum step size try running the simulation again with the default value auto Did you ask for too much accuracy The default relative tolerance 0 1 accuracy is usually sufficient For models with states that go to zero if the absolute tolerance parameter is too small the simulation may take too many steps around the near zero state values See the discussion of error in Error Tolerances on page 4 11 The time scale may be too long Reduce the time interval The problem may be stiff but you re using a nonstiff solver Try usingodel5s The model uses sample times that are not multiples of each other Mixing sample times that are not multiples of each other causes the solver to take small enough steps to ensure sample time hits for all sample times 4 19 4 Running a Simulation 4 20 e The model contains an algebraic loop The solutions to algebraic loops are iteratively computed at every time step Therefore they severely degrade performance For more information see Algebraic Loops in Chapter 10 e Your model feeds a Random Number block into an Integrator For continuous systems use the Band Limited White Noise block in the Sources library Improving Simulation Accuracy To check your simulation accuracy run the simulation over a reasonable time span Then reduce either the relative tolerance to le 4 the default is le 3 or
106. 3 C C MEX file S functions 8 2 8 26 callback parameters block 3 31 model 3 30 callback routines 3 30 canceling a command 3 3 capping unconnected blocks 9 145 cg_sfun h included in S function 8 28 changing annotations font 3 24 block icons font 3 10 block names font 3 10 block names location 3 10 block size 3 9 sample time during simulation 10 11 signal labels font 3 23 check box control type 6 13 Chirp Signal block 9 18 Clear menu item 3 8 Clock block 9 19 example 5 3 Close Browser menu item 3 42 Close button on Mask Editor 6 9 Close menu item 2 3 Close M odel menu item 3 42 close_system command 11 8 Closefcn block callback parameter 3 31 CloseFcn model callback parameter 3 30 closing block dialog boxes 11 8 model windows 11 6 system windows 11 8 clutch demo 9 75 colors for sample times 10 13 Combinatorial Logic block 9 20 combining input lines into vector line 9 101 Communications Toolbox 1 5 conditionally executed subsystems 7 2 connecting blocks 2 10 3 17 connecting lines to input ports 2 11 Connections block library 9 7 block parameters A 10 consistency checking 4 17 Constant block 9 23 constant sampletime 10 9 constant value generating 9 23 Continue menu item 4 5 continuous block setting sample time 8 46 continuous state S function example 8 15 8 32 control input 7 2 control signal 7 2 Control System Toolbox 1 6 linearization 5 5 1 3 Index 1 4 control type 6 12 check box 6 13 edit 6 12
107. 3 ode2 odel discrete Rel Tol Relative error tolerance scalar le 3 AbsTol Absolute error tolerance scalar le 6 Refine Refine factor scalar 1 MaxStep Maximum step size scalar auto Initial Step Initial step size scalar auto FixedStep Fixed step size scalar auto Max Order Maximum order for ode15s 1 2 3 4 5 Out put Option Output option Additional OutputTimes RefineOut putTimes SpecifiedOut put Ti mes Out put Ti mes Values for chosen Out put Option vector LoadExternallnput Load input from workspace on off Externall nput SaveTi me Ti meSaveName SaveState StateSaveName SaveQOut put Out put SaveName Loadinitial State Time and input variable names Save simulation time Simulation time name Save states State output name Save simulation output Simulation output name Load initial state scalar or vector t u on off variable to on off variable xo on off variable yo on off we we ro M odel Parameters Table A 1 Model Parameters Continued Parameter Description Values Initial State SaveFinalState Final StateName Li mi t MaxRows ax Rows Deci mation AlgebraicLoopMsg inStepSizeMsg Unconnectedinput Msg UnconnectedOut put Msg UnconnectedLineMsg ConsistencyChecking ZeroCross Closefen PreLoadFcn PostLoadFcn SaveFcn StartFen StopFen Initial state name or values Save final state
108. 3 41 to PostScript file 3 41 proceeding with suspended simulation 4 5 produce additional output option 4 12 produce specified output only option 4 13 Product block 9 106 algebraic loops 10 7 programmable logic arrays modeling 9 20 prompts control types 6 12 creating 6 11 deleting 6 11 editing 6 11 inserting 6 11 masked block parameters 6 10 moving 6 12 propagation of signal labels 3 23 properties of Scope block 9 126 Pulse Generator block 9 108 purely discrete systems 10 11 QFT Control Design Toolbox 1 8 Quantizer block 9 109 modeling A D converter 9 164 1 13 Index question marks in masked block icon 6 19 6 20 Quit MATLAB menu item 2 13 3 45 Quit menu item 2 13 3 45 R randn function 9 111 random noise generating 9 132 Random Number block 9 111 and Band Limited White Noise block 9 16 simulation speed 4 20 random numbers generating normally distribut ed 9 16 Rate Limiter block 9 113 reading data from data store 9 26 from file 9 66 from workspace 9 68 Real Time Workshop 1 10 Real Time Workshop Ada Extension 1 12 Redo menu item 3 3 reentrancy 8 48 reference block 3 14 reference block definition 3 13 refine factor 4 12 4 26 region of zero output 9 28 Relational Operator block 9 115 zero crossings 10 6 relative tolerance 4 11 4 26 simulation accuracy 4 20 Relay block 9 117 zero crossings 10 6 Repeating Sequence block 9 118 replace block command 11 20 replacing blocks in model 11 20 reset outpu
109. 6 20 Simulink displays three question marks in the block icon and issues warnings in these situations e When the values for the parameters used in the drawing commands are not yet defined for example when the mask is first created and values have not yet been entered into the mask dialog box e When a masked block parameter or drawing command is entered incorrectly Displaying a Transfer Function on the Block Icon Todisplay a transfer function equation in the block icon enter the following command in the Drawing commands field dpoly num den dpoly num den character num and den are vectors of transfer function numerator and denominator coefficients typically defined using initialization commands The equation is expressed in terms of the specified character Thedefault iss When the icon is drawn the initialization commands are executed and the resulting equation is drawn on the icon e To display a continuous transfer function in descending powers of s enter dpoly num den 6 19 6 Using M asks to Customize Blocks 6 20 For example for num 0 0 1 andden 1 2 1 theicon looks like this 1 s 25 1 e Todisplay a discrete transfer function in descending powers of z enter dpoly num den z For example for num 0 0 1 andden 1 2 1 theicon looks likethis 1 z gt 2z 1 e Todisplay a discrete transfer function in ascending powers of 1 z enter dpoly num den z
110. 65 0275 10 4 5 2 0 2529 5 45 The step size of the fixed step discrete solver is the fundamental sample time The variable step di scr ete solver takes the largest possible steps Variable step solvers You can choose these variable step solvers 0de45 0de23 odell3 odel5s ode23s anddiscrete The default isode45 for systems with states or discrete for systems with no states e ode45 is based on an explicit Runge Kutta 4 5 formula the Dormand Prince pair It is a one step solver that is in computing y t it needs only the The Simulation Parameters Dialog Box solution at the immediately preceding time point y t _7 In general ode45 is the best solver to apply as a first try for most problems ode23 is also based on an explicit Runge Kutta 2 3 pair of Bogacki and Shampine It may be more efficient than ode45 at crude tolerances and in the presence of mild stiffness ode23 is a one step solver ode113 isa variable order Adams Bashforth M oulton PE CE solver It may be more efficient than ode45 at stringent tolerances ode113 is a multistep solver that is it normally needs the solutions at several preceding time points to compute the current solution odel5s iS a variable order solver based on the numerical differentiation formulas NDF s These are related to but are more efficient than the backward differentiation formulas BDF s also known as Gear s method Likeodell3 odel5s iS a multistep method solver If
111. 75 Gain m Block BlockType Sum Na me Sum Position 185 72 215 103 Inputs Block BlockType Out port Name mye Position 255 80 275 100 Port 1 Output WhenDisabled held Initial Output O A Sample M odel File Line SrcBlock SrcPort Dst Bl ock DstPort Line SrcBlock SrcPort Dst Block DstPort Line SrcBlock SrcPort Points Dst Block DstPort Line SrcBlock SrcPort Points Dst Block DstPort Line Name Labels SrcBl ock SrcPort Points Branch Points Dst Bl ock Dst Port Gain 25 0 u Sum Out put mal Ae 0 mx b 1 135 0 0 60 To Workspace 1 B M odel File Format Branch Dst Bl ock Scope Dst Port 1 Line Name Input Labels 0 0 SrcBlock Sine Wave SrcPort 1 Dst Block mx b DstPort 1 Annotation Position 215 65 Text Sample Masked System B 10 The SimStruct C The SimStruct This table provides the names and descriptions of the macros that get and set values in the SimStruct structure which isinsi mstruc h locatedinsi mul i nk include Any macros not documented are reserved for use by The MathWorks and should not be used by S functions The SimStruct is the structure that describes S functions which are described in Chapter 8 Macro Description ssGet Model Name S Get name of model ssGet Pat h S Get path of model ssGet ParentSS
112. C4 fi i O wo Cy P Algebraic Constraint Display z4 Sum 22 22 21 1 Solve 22 P O wen Algebraic Constraint1 Display z2 Algebraic Constraint p Algebraic Constraint mask Constrains input signal f z to zero and outputs an algebraic state z This block outputs the value necessary to produce a zero at the input The output must affect the input through some feedback path Provide an initial guess of the output to improve algebraic loop solver efficiency Parameters Initial guess 0 Apply Revert Help An initial guess of the solution value The default is 0 Algebraic Constraint Characteristics Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving block No Yes No 9 11 Backlash 9 12 Purpose Library Description ab Model the behavior of a system with play Nonlinear The Backlash block implements a system in which a change in input causes an equal change in output However when the input changes direction an initial change in input has no effect on the output The amount of side to side play in the system is referred to as the deadband The deadband is centered about the output This figure shows the block s initial state with the default deadband width of 1 and initial output of 0 1 0 0 5 0 0 5 1 0 nA deadband gt Output A system with play c
113. Declaration Arguments Description Example 8 55 Compute derivatives for continuous states static void mdl Derivatives double dx double x double u SimStruct S int tid double dx The derivatives vector returned double The states vector both continuous and discrete double u Theinput vector SimStruct 5 Thesimstruct for this block int tid Thetask ID for use with multitasking real time operating systems The mdi Derivatives function computes the derivatives for the S function s continuous states where the derivative is a function of time the states and the input as shown in the equation below He falt x u Simulink calls the mdi Deri vati ves function at each major and minor integration step The input arguments are the states at the previous time value the current inputs thesi mStruct and a task ID Thetask ID is used when the system is executing in a multithreaded environment static void mdli Derivatives double dx double x double wu SimStruct S int tid int ii Compute the derivatives for a basic integrator where dx is equal to the input for i 0 i lt ssGetNumContStates S i dx i uli mdllnitializeConditions Purpose Initialize states and work vectors Declaration static void mdlInitializeConditions double x0 SimStruct S Arguments double 0 The initial states continuous and discrete vector returned SimStruct 5 Thesimstruct for this block
114. Displaying Vector Signals The Scope can display up to 30 signals When more than one signal is displayed the Scope uses different colors in this order yellow magenta cyan red green and dark blue When morethan six signals are displayed the Scope cycles through the colors in the order listed above 9 121 Scope 9 122 Using the Scope as a Floating Scope A floating Scope is a Scope block that can display the signals carried on one or more lines To add a floating Scope to a model copy a Scope block into the model window then open the block Select the Properties button on the block s toolbar the right most button Then select the Settings tab and select the Floating scope check box Tousea floating Scope during a simulation first open the block To display the signals carried on a line select the line Hold down the Shift key while clicking on another line to select multiple lines It may be necessary to press the Auto scale data button on the Scope s toolbar to find the signal and adjust the axes to the signal values A model can contain more than one floating Scope although it is not useful to have more than one floating Scope in a window This figure shows the Scope block displaying the output of thevdp model The simulation was run for 40 seconds Note that this scope shows the final 20 seconds of the simulation The Time offset field displays the number of seconds on previous screens Ed vdp Scope DAA I
115. Fixed Point Blockset 0 000 cece eee eee 1 14 The Nonlinear Control Design Blockset 1 15 Quick Start Running a Demo Model z zeunnnnunnnnnnnnnnnnn 2 2 Description of the Demo 0 cece eee 2 3 SomeThingStOTry 0 02 cece tee 2 4 What This Demo Illustrates 0 000000 e eee 2 4 Other Useful Demos 00 0 e eee 2 5 Contents Contents Building a Simple Model zzunnnonnnonnnunnnnnnnn 2 6 3 Starting Simulink sssssssssasssunsssnssasnussennnsnnn 3 2 Simulink Windows sssaaa eaaa 3 3 Creating a New Model 0 0 cee eee 3 3 Editing an Existing Model 0 0 20 e eee eee 3 3 Undoing a Command een een eae 3 3 Selecting Objects ccc cece cece eee eee 3 4 Selecting One Object 0 cee es 3 4 Selecting More than One Object 00 cee eee 3 4 Blocks cece cece 3 6 Copying and Moving Blocks from One Window to Another 3 6 Moving Blocks in a Moda 0 0c eee eee eee 3 7 Duplicating Blocks in a Model 20 0c eee eee 3 7 Specifying Block Parameters 0 00 c cee a 3 7 DeletingBlockS 2 2 cece eee 3 8 Changing the Orientation of Blocks 0000000 3 8 RESIZING BIOCKS 1 2 ceo ua Gites gun tee ace iw goat 3 9 Manipulating Block Names 0 00 e eee eee ee 3 9 Disconnecting BIOCKS 0 00 eee eee 3 10 Vector Input and Output 0
116. Function M in f Number of Input Ports 1 Apply Revert Help Direct Feedthrough Yes The function mi n or max to apply to the input The number of inputs to the block Sample Time Inherited from the driving block Scalar Expansion Of the inputs Vectori zed Yes Zero Crossing Yes to detect minimum and maximum values Multiport Switch Purpose Library Description Choose between block inputs Nonlinear The Multiport Switch block chooses between a number of inputs The first top input is the control input and the other inputs are the switch inputs The value of the control input determines which switch input to pass through to the output port Simulink rounds the control input value to the nearest positive integer and passes the switch input that corresponds to that value according to this table This control input value Passes this switch input Up to 1 4999 First From 1 5 to 2 4999 Second From 2 5 to 3 4999 Third etc etc Switch inputs can be scalar or vector The control input can be a scalar or a vector The block output is determined by these rules e If inputs are scalar the output is a scalar e If the block has more than one switch input at least one of which is a vector the output is a vector Any scalar inputs are expanded to vectors e f the block has only one switch input and that input is a vector the block output is the element of the vec
117. Gain Gain Gain scalar or vector 1 Integrator Integrator ExternalReset External reset none rising falling either InitialConditionSource Initial condition source internal external Initial Condition Initial condition scalar or vector 0 Limit Out put Limit output off on A 14 Block Specific Parameters Table A 5 Linear Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values UpperSaturationlimit LowerSaturationlimit ShowSat urationPort ShowStatePor AbsoluteTolerance Upper saturation limit Lower saturation limit Show saturation port Show state port Absolute tolerance Matrix Gain Matrix Gain masked Slider Gain S i der Gai n masked State Space St at eSpace A B C D X0 Sum S um Inputs Transfer Fen Transf erFcn Numerator Denomi nator Zero Pole Zer oPol e Zeros Poles Gain o u gt D Initial conditions List of signs Numerator Denominator Zeros Poles Gain scalar or vector inf scalar or vector inf off on off on scalar auto matrix 1 matrix 1 matrix 1 matrix 1 vector 0 scalar or list of signs vector or matrix 1 vector 1 1 vector 1 vector 0 1 vector 1 A 15 A Model and Block Parameters Table A 6 Nonlinear Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Abs A
118. How Simulink W orks Calculating these derivatives is a two step process First each block s output is calculated in the order determined during the sorting Then in a second pass each block calculates its derivatives based on the current time its inputs and its states The resulting derivative vector is returned to the solver which uses it to compute a new state vector at the next time point Once a new state vector is calculated the sampled data blocks and Scope blocks are updated Zero Crossings Simulink uses zero crossings to detect discontinuities in continuous signals Zero crossings play an important role in e The handling of state events e The accurate integration of discontinuous signals State Event Handling A system experiences a stateevent when a change in the value of a state causes the system to undergo a distinct change A simple example of a state event isa bouncing ball hitting the floor When simulating such a system using a variable step solver the solver typically does not take steps that exactly correspond to the times that the ball makes contact with the floor As a result the ball is likely to overshoot the contact point which results in the ball penetrating the floor Simulink uses zero crossings to ensure that time steps occur exactly within machine precision at the time state events occur Because time steps occur at the exact time of contact the simulation produces no overshoot and the transition
119. Index 1 8 icon frame mask property 6 21 Icon page of Mask Editor 6 9 icon rotation mask property 6 21 icon transparency mask property 6 21 icons creating for masked blocks 6 6 6 17 graphics on 6 18 text on 6 17 transfer functions on 6 19 Image Processing Toolbox 1 7 improved Euler formula 4 10 inf values in mask plotting commands 6 19 Infinite Impulse Response filter 9 37 inherited sample times 8 9 I nit Fen block callback parameter 3 31 initial conditions defining vector example 8 48 determining 4 16 order of states 8 48 setting 9 77 S F unction block 8 47 S functions 8 56 specifying 4 15 initial states 4 25 initial step size 4 10 4 11 4 25 simulation accuracy 4 20 initialization commands 6 14 debugging 6 16 Initialization page of Mask Editor 6 9 Inport block 9 78 in subsystem 3 28 3 29 9 141 linearization 5 4 i nmod function 5 9 supplying input to mode 4 14 input ports unconnected 9 74 inputs adding 9 142 applying expressions to 9 61 applying MATLAB function to 9 61 9 94 choosing between 9 99 combining into vector line 9 101 constraining 9 10 delaying and holding 9 159 delaying by specified time 9 164 delaying by variable amount 9 160 dynamically sized 8 8 external 4 23 from outside system 9 78 from previous time step 9 97 from workspace 9 79 9 80 generating step between two levels 9 139 loading from base workspace 4 14 logical operations on 9 85 mixing vector and scalar 3 11 multiplying 9 70 outp
120. Library Description hth Perform piecewise linear mapping of the input Nonlinear The Look Up Table block maps an input to an output using linear interpolation of the values defined in the block s parameters You define the table by specifying either as row or column vectors the Vector of input values and Vector of output values parameters The block produces an output value by comparing the block input with values in the input vector e If it finds a value that matches the block s input the output is the corresponding element in the output vector e f it does not find a value that matches it performs linear interpolation between the two appropriate elements of the table to determine an output value If the block input is less than the first or greater than the last input vector element the block extrapolates using the first two or the last two points To map two inputs to an output use the Look Up Table 2 D block For more information see page 9 89 Tocreate a table with step transitions repeat an input value with different output values For example these input and output parameter values create the input output relationship described by the plot that follows Vector of input values 2 1 1 0001 2122 1 2 Vector of output values 1 1 2 11 the output value This example has three step discontinuities at u 1 0 and 9 87 Look Up Table 9 88 Parameters and Dialog Box Ch
121. REE_CODE Do not specify theSS_ OPTI ON_EXCEPTI ON_FREE_CODE option if the S function contains any routines that can throw an exception e All routines that start with mex can throw an exception e Routines that start with mx can throw an exception except routines that get a pointer or determine the size of parameters such as mxGet Pr mxGet Data mxGet Number Of Di mensions mxGet M mxGetN and mxGet Number Of Elements If the S function must allocate memory avoid using mx Cal oc Instead use the stdlib h calloc routine directly and perform your own error handling then free the memory in md Ter mi nate 8 53 8 S Functions 8 54 Error Handling Error handling works consistently across the Real Time Workshop and Simulink Toreport an error S functions should include these statements ssSetErrorStatus S Error string return It is important that Error string be persistent memory not a stack variable sfun_errhdl c shows how to perform error checking TheS function checks to see that required parameters are of the correct format Normal or Real Time Workshop Simulation S functions can determine if they are running in a normal simulation as part of Real Time Workshop code generation or as part of external mode This is done usingss Get Si mMode S Additional Macros in mdllnitializeSizes ThessGetPath ssGet Model Name andssSet Status macros work in mdl I nitializeSizes mdIDerivatives Purpose
122. S Get parent subsystem or system SimStruct ssGetNumCont States S Get number of continuous states ssSetNumCont States S nContStates Set number of continuous states ssGetNumDiscStates S Get number of discrete states ssSetNumDiscStates S nDiscStates Set number of discrete states ssGetNumTotalStates S Get total number of states continuous and discrete ssGetNumQutputs Get number of outputs ssSetNumOut puts S nOut puts Set number of outputs ssGetNuml nputs S Get number of inputs ssSetNuml nputs S nlnputs Set number of inputs ssl sDirectFeedThrough S Direct feedthrough flag ssSetDirectFeedThrough S dirFeed Set direct feedthrough flag ssGet NumRWor k S Get size of real work vector sssetNumRWor k S nRWork Set size of real work vector ssGetNuml Wor k S Get size of integer work vector ssSetNuml Wor k S nl Work Set size of integer work vector Macro Description ssGetNumPWork 5 ssSetNumPWork S nPWork ssGetNumSFcnParams S ssSetNumSFcnParams S nSFcnPar ams ssGetSFcnParam S index ssGe ssSe ssGe ssGe ssGe ssGe ssGe ssGe NumSampl eTi mes S NumSampl eTi mes S nSampl eTi mes U S X 5 dX 5 ContStateDisabled S Wor k S WorkValue S iworkl dx ssSet WorkVal ue S iworkldx iworkVal ue ssGe ssGe RWork 5 RWorkValue S rworkl dx ssSetRWorkVal ue S rworkl dx rworkVal ue ssGet PWork S ssGet PWorkVal ue S pworkl dx
123. SIMULINK n Dynamic System Simulation for MATLAB Modeling Simulation Implementation User s Guide Version 2 1 X OD o E How to Contact The MathWorks 508 647 7000 508 647 7001 The MathWorks Inc 24 Prime Park Way Natick MA 01760 1500 http www mathworks com ftp mathworks com comp soft sys matlab Support mat hworks com Suggest mat hworks com bugs mat hworks com doc mathworks com subscribe mathworks com service mathworks com info mat hworks com Simulink User s Guide Phone Fax Mail Web Anonymous FTP server Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Subscribing user registration Order status license renewals passcodes Sales pricing and general information COPYRIGHT 1984 1997 by The MathWorks Inc All Rights Reserved The software described in this document is furnished under a license agreement Thesoftware may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or repro duced in any form without prior written consent from The MathWorks Inc U S GOVERNMENT If Licensee is acquiring the software on behalf of any unit or agency of the U S Government the following shall apply a for units of the Department of Defense RESTRICTED RIGHTS LEGEND Use duplication or disclosure by the Government is subject to restric tions as set forth in subp
124. Sample Time Inherited from driving block Vectorized Yes 9 145 To File Purpose Library Description untitled mat 9 146 Write data to a file Sinks The To File block writes its input to a matrix in aMAT file The block writes one column for each time step the first row is the simulation time the remainder of the column is the input data one data point for each element in the input vector The matrix has this form ty t2 tinal ul ul vdeo un Un UNE nal The From File block can use data written by a To File block without any modifications However the form of the matrix expected by the From Workspace block is the transpose of the data written by the To File block The block writes the data as well as the simulation time after the simulation is completed The block icon shows the name of the specified output file The amount of data written and the time steps at which the data is written are determined by block parameters e The Decimation parameter allows you to write data at every nth sample where n is the decimation factor The default decimation 1 writes data at every time step The Sample time parameter allows you to specify a sampling interval at which to collect points This parameter is useful when using a variable step solver where the interval between time steps may not be the same The default value of 1 causes the block to inherit the sample time from the driving block when determin
125. Simulink session 3 45 termination of simulation 8 63 Terminator block 9 145 text command 6 17 text on masked block icons 6 17 tf2ss utility 9 151 time delay simulating 9 153 time interval and simulation speed 4 19 tips for building models 3 33 To File block 9 146 To Workspace block 9 148 example 5 3 toolboxes 1 5 Communications Toolbox 1 5 Control System Toolbox 1 6 Financial Toolbox 1 6 Frequency Domain System Identification Tool box 1 6 Fuzzy Logic Toolbox 1 6 Higher Order Spectral Analysis Toolbox 1 7 Image Processing Toolbox 1 7 LMI Control Toolbox 1 7 Model Predictive Control Toolbox 1 7 Mu Analysis and Synthesis Toolbox 1 7 NAG Foundation Toolbox 1 7 Neural Network Toolbox 1 8 Optimization Toolbox 1 8 Partial Differential Equation Toolbox 1 8 QFT Control Design Toolbox 1 8 Robust Control Toolbox 1 8 Signal Processing Toolbox 1 9 Spline Toolbox 1 9 Statistics Toolbox 1 9 Symbolic Math Toolbox 1 9 Index System Identification Toolbox 1 9 Wavelet Toolbox 1 9 tracing facilities 4 27 Transfer Fcn block 9 151 algebraic loops 10 7 example 3 36 linearization 5 5 transfer function form converting to 5 12 transfer functions discrete 9 48 linear 9 151 masked block icons 6 19 poles and zeros 9 165 poles and zeros discrete 9 50 transparent icon 6 21 Transport Delay block 9 153 linearization 5 5 Trapezoidal method 9 43 Trigger block 9 155 creating triggered subsystem 7 9 outputting trigger signal 7 10 showing output po
126. System buttons By default Simulink does not display contents of masked blocks and blocks that are library links These check boxes enable you to override the default e The block type of the selected block Dialog box buttons Help Print and Close Interpreting List Contents Simulink identifies masked blocks reference blocks blocks with defined OpenFcn parameters and systems that contain subsystems using these symbols before a block or system name A plus sign before a system name in the systems list indicates that the system is expandable which means that it has systems beneath it Double click on the system name to expand the list and display its contents in the blocks list When a system is expanded a minus sign appears before its name M indicates that the block is masked having either a mask dialog box or a mask workspace For more information about masking see Chapter 6 L indicates that the block is a reference block For more information see Libraries on page 3 13 O indicates that an open function OpenF cn callback is defined for the block For more information about block callbacks see Using Callback Routines on page 3 30 S indicates that the system is a Stateflow block 3 Creating a M odel 3 44 Opening a System You can open any block or system whose name appears in the blocks list To open a system 1 Inthesystems list select by single clicking on the name of the p
127. The default is 1 Denominator The row vector of denominator coefficients The defaultis 1 1 01 Apply Revert Help Characteristics Direct Feedthrough Only ifthelengths of the Numerator and Denominator parameters are equal Sample Time Continuous Scalar Expansion No States Length of Denominator 1 Vectorized Yes Zero Crossing No 9 152 Transport Delay Purpose Library Description EN Delay the input by a given amount of time Nonlinear The Transport Delay block delays the input by a specified amount of time It can be used to simulate a time delay At the start of the simulation the block outputs the Initial input parameter until the simulation time exceeds the Time delay parameter when the block begins generating the delayed input The Time delay parameter must be nonnegative The block stores input points and simulation times during a simulation in a buffer whose initial size is defined by the Initial buffer size parameter If the number of points exceeds the buffer size the block allocates additional memory and Simulink displays a message after the simulation that indicates the total buffer size needed Because allocating memory slows down the simulation define this parameter value carefully if simulation speed is an issue F or long time delays this block might usea large amount of memory particularly for a vectorized input When output is required at a time that does not correspond
128. The time interval between samples Apply Revert Help Discrete Zero Pole Characteristics Direct Feedthrough Sample Time Scalar Expansion States Vectorized Zero Crossing Yes if the number of zeros and poles are equal Discrete No Length of Poles vector No No 9 51 Discrete Zero Pole 9 52 Discrete Zero Pole 9 53 Discrete Zero Pole 9 54 Discrete Zero Pole 9 55 Discrete Zero Pole 9 56 Display Purpose Library Description Show the value of the input Sinks The Display block shows the value of its input You can control the display format by selecting a Format choice e short which displays a 5 digit scaled value with fixed decimal point e ong which displays a 15 digit scaled value with fixed decimal point e short_e which displays a 5 digit value with a floating decimal point e ong_e which displays a 16 digit value with a floating decimal point e bank which displays a value in fixed dollars and cents format but with no or commas Touse the block as a floating display select the Floating display check box The block s input port disappears and the block displays the value of the signal on a selected line The amount of data displayed and the time steps at which the data is displayed are determined by block parameters e The Decimation parameter enables you to display data at every nth sample wheren is the decimation factor Th
129. Ti me Sample time scalar sample period 1 or vector period offset Demux De mux Out puts Number of outputs scalar or vector 3 A 10 Block Specific Parameters Table A 3 Connections Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Enable Enabl ePort StatesWhenEnabling ShowOut put Port From From GotoTag Goto Got o GotoTag TagVisibility States when enabling Show output port Goto tag Tag Tag visibility Goto Tag Visibility GotoTagVisi bility GotoTag Goto tag Ground Gr ound no block specific parameters IC I ni Val tial Condition ue In Inport Port Port Width Sampl eTi me Mux Mux I np Out 0u Por Ou gt uts tport put WhenDisabl ed ial Out put Initial value Port number Port width Sample time Number of inputs Port number Output when disabled Initial output held reset off on tag A tag A local scoped global tag A scalar or vector 1 scalar 1 scalar 1 scalar sample period 1 or vector period offset scalar or vector 3 scalar 1 held reset scalar or vector 0 A 11 A Model and Block Parameters Table A 3 Connections Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Selector Selector Elements Elements vector
130. Use this block rather than the Clock block which outputs continuous time when you need the current time within a discrete system Parameters Digital Clock r Digital Clock a nd Dia log Outputs current simulation time at the specified rate Box Parameters Sample time The sampling interval The default value is 1 second Apply Revert Help Characteristics SampleTime Discrete Scalar Expansion No Vectori zed No Zero Crossing No 9 36 Discrete Filter Purpose Library Description Parameters and Dialog Box Implement IIR and FIR filters Discrete The Discrete Filter block implements Infinite Impulse Response IIR and Finite Impulse Response FIR filters You specify the coefficients of the numerator and denominator polynomials in ascending powers of z as vectors using the Numerator and Denominator parameters The order of the denominator must be greater than or equal to the order of the numerator See the Discrete Transfer F cn block description on page 9 48 for more information about coefficients The Discrete Filter block represents the method often used by signal processing engineers who describe digital filters using polynomials in z the delay operator The Discrete Transfer Fcn block represents the method often used by control engineers who represent a discrete system as polynomials in z The methods are identical when the numerator and denominator are the same length A vector
131. You can run a simulation from the command line using thesi m command or theset_ param command Both are described below Using the sim Command The full syntax of the command that runs the simulation is t x y sim model timespan options ut pl pn Only the mode parameter is required Parameters not supplied on the command are taken from the Simulation Parameters dialog box settings For detailed syntax for thes i m command see page 4 22 The opti ons parameter is a structure that supplies additional simulation parameters including the solver name and error tolerances You define parameters in the options structure using thesi mset command described on page 4 24 The simulation parameters are discussed earlier in this chapter Using the set param Command You can usetheset param command to start stop pause or continue a simulation or update a block diagram Similarly you can use theget_ param command to check the status of a simulation The format of theset_param command for this use is set_param sys Simul ationCommand cmd where sys isthenameofthesystemand cmd is start stop pause continue Or update The format of the get _par am command for this use is get_param sys Simul ationStatus Simulink returns stopped initializing running paused terminating and external used with Real Time Workshop 4 21 sim Purpose Simulate a Simulink model Syntax t x y
132. a simulation is started by evaluating the width of the input vector driving the S function The input width can also be used to determine the number of continuous states the number of discrete states and the number of outputs Toindicate that the input width is dynamically sized specify a value of 1 for the appropriate fields in thesi zes structure which is returned during the mdli Initialize call You can determine the actual input width when your S function is called by using ength u Introduction For example the illustration below shows two instances of the same S Function block in a model hux S Function Clock S Function1 The upper S F unction block is driven by a block with a three element output vector The lower S F unction block is driven by a block with a scalar output By specifying that the S F unction block has dynamically sized inputs the same S function can accommodate both situations Simulink automatically calls the block with the appropriately sized input vector Similarly if other block characteristics such as the number of outputs or the number of discrete or continuous states are specified as dynamically sized Simulink defines these vectors to be the same length as the input vector Setting Sample Times and Offsets If the S Function block s behavior is a function of discrete time intervals you can define a sample timeto control when Simulink calls the block You can also define an offset tha
133. absolute tolerance for 9 83 between trigger events 7 10 determining 10 3 initial 4 16 4 25 initial conditions vector order 8 48 loading initial 4 15 ordering of 4 16 outputting 4 26 resetting 9 83 saving at end of simulation 4 25 saving final 4 15 4 16 updating 10 11 updating discrete in S function 8 64 when enabling 7 5 writing to workspace 4 15 State Space block 9 137 algebraic loops 10 7 Statistics Toolbox 1 9 Step block 9 139 zero crossings 10 6 step size 4 10 1 17 Index 1 18 accuracy of derivative 9 34 simulation speed 4 19 stiff problems 4 9 stiff systems and simulation time 4 19 Stop menu item 2 3 2 12 4 5 Stop Simulation block 9 140 stop time 4 7 Stop Time parameter 2 12 StopFcn block callback parameter 3 32 St opFcn model callback parameter 3 30 stopping simulation 9 140 Subsystem block 9 141 adding to create subsystem 3 28 opening 3 29 zero crossings 10 6 subsystems and Inport blocks 9 78 creating 3 27 3 32 labeling ports 3 29 model hierarchy 3 33 path 11 3 underlying blocks 3 29 Sum block 9 142 algebraic loops 10 7 summary of mouse and keyboard actions 3 25 suspending simulation 4 5 Switch block 9 144 zero crossings 10 6 switching output between inputs 9 92 9 144 switching output between values 9 117 Symbolic Math Toolbox 1 9 System Identification Toolbox 1 9 System section of md file B 3 systems current 11 16 path 11 3 T terminating MATLAB 2 13 terminating Simulink 2 13 terminating
134. ace form that can be further converted to transfer function or zero pole gain form usingtf orzpk Linearizing a model that contains Derivative or Transport Delay blocks can be troublesome F or more information see Linearization on page 5 4 Trim Analysis Purpose Syntax Description Determine steady state parameters that satisfy input output and state conditions x u y dx trim sys x u y dx trim sys x0 u0 y0 x u y dx trim sys x0 u0 y0 ix iu iy x u y dx trime sys x0 u0 y0 ix iu iy dx0 idx x u y dx trim sys x0 u0 y0 ix iu iy dx0 idx options x u y dx trim sys x0 u0 y0 ix iu iy dx0 idx options t x u y dx options trim sys trim attempts to find values for the inputs u and states x that set the state derivatives tozero Such a point is Known as an equilibrium point which occurs when the system is in steady state Since the problem is usually not unique specific values of thestatex theinput u and the outputs y can often be fixed x u y trim sys triestofind an equilibrium point such that the maximum absolute value of x x0 u y is minimized x0 is the initial state of the system You can obtain x0 using this command sizes x0 xstr sys 0 x u y trim sys x0 u0 y0 specifies initial starting guesses for x u and y Here the maximum value of abs x x0 u u0 y y0 is minimized Individual elements of x u andy can be fixed
135. al to the Threshold parameter the block propagates thefirst input otherwise it propagates thethird input This figure shows the use of the block ports If control gt threshold Control input x Output If control lt threshold Switch To drive the switch with a logic input i e O or 1 set the threshold to 0 5 Switch Passes through input 1 when input 2 is greater than or equal to threshold otherwise passes through input 3 Parameters Threshold Apply Revert Help Direct Feedthrough Yes The value of the control the second input at which the switch flips to its other state You can specify this parameter as either a scalar or a vector equal in width to the input vectors Sample Time Inherited from driving block Scalar Expansion Yes Vectori zed Yes Zero Crossing Yes to detect when the switch condition occurs Terminator Purpose Library Description Parameters and Dialog Box Characteristics Terminate an unconnected output port Connections The Terminator block can be used to cap blocks whose output ports are not connected to other blocks If you run a simulation with blocks having unconnected output ports Simulink issues warning messages Using Terminator blocks to cap those blocks avoids warning messages Terminator Terminator Used to terminate output signals Prevents warnings about unconnected output ports j Help
136. an bein one of three modes e Disengaged in this mode the input does not drive the output and the output remains constant e Engaged in a positive direction in this mode the input is increasing has a positive slope and the output is equal to the input minus half the deadband width e Engaged in a negative direction in this mode the input is decreasing has a negative slope and the output is equal to theinput plus half the deadband width If theinitial input is outside the deadband the Initial output parameter value determines if the block is engaged in a positive or negative direction and the output at the start of the simulation is the input plus or minus half the deadband width F or example the Backlash block can be used to model the meshing of two gears The input and output are both shafts with a gear on one end and the output shaft is driven by theinput shaft E xtra space between the gear teeth introduce play The width of this spacing is the Deadband width parameter If the system is disengaged initially the output the position of the driven gear is defined by the Initial output parameter Backlash The figures below illustrate the block s operation when the initial input is within the deadband Thefirst figure shows the relationship between theinput and the output while the system is in disengaged mode and the default parameter values are not changed 1 0 0 5 0 0 5 1 0 Input within deadband Th
137. an contain blocks that are sampled at different rates Models can also be hybrid containing a mixture of discrete and continuous blocks Discrete Blocks Each of the discrete blocks has a built in sampler at its input and a zero order hold at its output When the discrete blocks are mixed with continuous blocks the output of the discrete blocks between sample times is held constant The outputs of the discrete blocks are updated only at times that correspond to sample hits Sample Time The Sample time parameter sets the sample time at which a discrete block s states are updated Normally the sample time is set to a scalar variable however it is possible to specify an offset time or skew by specifying a two element vector in this field For example specifying the Sample time parameter as thevector Ts offset sets thesampletimetoTs and the offset value toof f set The discrete block is updated on integer multiples of the sample time and offset values only t n Ts offset wheren is an integer andof fset can be positive or negative but less than the sampletime The offset is useful if some discrete blocks must be updated sooner or later than others You cannot change the sample time of a block while a simulation is running If you want to change a block s sample time you must stop and restart the simulation for the change to take effect Purely Discrete Systems Purely discrete systems can be simulated using any of t
138. an the period The sample time must be greater than zero Use the Discrete Pulse Generator block for discrete or hybrid systems To generate continuous signals use the Pulse Generator block described on page 9 108 Discrete Pulse Generator r Discrete Pulse Generator as integer multiples of the sample time Parameters Amplitude 1 Period number of samples 2 Pulse width number of samples 1 Phase delay number of samples 0 Sample time 1 Sample Time Scalar Expansion Vectorized Zero Crossing Generate pulses at regular intervals Specify parameters Apply Revert Help Discrete Of parameters Yes No The amplitude of the pulse The default is 1 The pulse period in number of samples The default is 2 The number of sample periods that the pulse is high The default is 1 The delay before each pulse is generated in number of samples The default is 0 The sample period The default is 1 9 39 Discrete State Space Purpose Library Description yin Camu xin F Aan Bun Implement a discrete state space system Discrete The Discrete State Space block implements the system described by x n 1 Ax n Bu n y n Cx n Du n where u is the input x is the state and y is the output The matrix coefficients must have these characteristics as illustrated in the diagram below A must be an n by n matrix where n is the number of states
139. appears after the simulation parameters and defines the default values for block parameters within this model These values can be overridden by individual block parameters defined in the Bl ock sections The AnnotationDefaults Section TheAnnotationDef aul ts section appears after the Bl ock Defaults section This section defines the default parameters for all annotations in the model These parameter values cannot be modified using thes et _param command The System Section The top level system and each subsystem in the model are described in a separate System section Each Syst em section defines system level parameters and includes Bl ock Line andAnnotati on sections for each block line and annotation in the system Each Li ne that contains a branch point includes a Branch section that defines the branch line B M odel File Format A Sample Model File This model file describes the samplesystem that illustrates masking described in Chapter 6 The model and subsystem look like this Sample Masked System Constant The mx b subsystem The model file mask_ example Model Name Version Si mParamPage Sampl eTi meCol ors Wi deVectorLines PaperOrientation StartTi me StopTi me Solver Rel Tol AbsTol Refine MaxStep Initial Step md follows mask example 2 00 Solver off off landscape 0 0 100 ode45 le 3 le 6 ye auto auto A Sample M odel File
140. appears on the block icon Use the Rounding F unction block instead of the Fcn block when you want vectorized output because the Fcn block can produce only scalar output Rounding Function r Rounding Rounding operations Parameters Function Therounding function Apply Revert Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion N A Vectorized Yes Zero Crossing No 9 119 Saturation Purpose Library Description Parameters and Dialog Box Characteristics 9 120 Limit the range of a signal Nonlinear The Saturation block imposes upper and lower bounds on a signal When the input signal is within the range specified by the Lower limit and Upper limit parameters theinput signal passes through unchanged When the input signal is outside these bounds the signal is clipped to the upper or lower bound When the parameters are set to the same value the block outputs that value Saturation Saturation r Parameters Upper limit 0 5 Lower limit 0 5 Apply Revert Help Limits input signal to the upper and lower saturation The upper bound on the input signal Whilethe signal is above this value the block output is set tothis value The lower bound on the input signal While the signal is below this value the block output is set tothis value Direct Feedthrough Sample Time Scalar Expansion Vectori zed Zero Cros
141. ar TheRelational Operator block performs a relational operation on its twoinputs and produces output according to the following table Operator Output TRUE if thefirst input is equal to the second input l TRUE if the first input is not equal to the second input lt TRUE if the first input is less than the second input lt TRUE if the first input is less than or equal to the second input gt TRUE if the first input is greater than or equal to the second input gt TRUE if the first input is greater than the second input If the result is TRUE the output is 1 if FALSE it is 0 You can specify inputs as scalars vectors or a combination of a scalar and a vector e For scalar inputs the output is a scalar e For vector inputs the output is a vector where each element is the result of an element by element comparison of the input vectors e For mixed scalar vector inputs the output is a vector where each element is the result of a comparison between the scalar and the corresponding vector element The block icon displays the selected operator 9 115 Relational Operator 9 116 Parameters and Dialog Box Characteristics Relational Operator Relational Operator Relational operators Parameters Operator Apply Revert Help Direct Feedthrough Yes The relational operator to be applied to the block inputs Sample Time Inherited from driving block Scalar Expan
142. ar the block separates the input signal into that number of output signals The widths of the output signals depend on the width of the input vector and the number of outputs e f theinput signal width is equal to the number of outputs the block separates the input signal vector into scalar signals In this model the Demux block separates a 3 element vector signal into 3 scalar signals The Number of outputs parameter is 3 Constant Number of outputs Display2 e If theinput signal width is evenly divisible by the number of outputs the block separates the input signal into vector signals of equal width In this model the Demux block separates a 12 element vector signal into 3 vector signals each with a width of 4 elements Terminator width Constant Number of outputs 3 Width2 Terminator e ftheinput signal width is not evenly divisible by thenumber of outputs and they re not the same the block separates the input signal into vector signals 9 30 Demux of unequal width and Simulink issues a warning message In this model the Demux block separates a 4 element vector signal into 3 signals The first signal contains the first two elements of the input signal Constant Number of outputs 3 Display2 Vector Number of Outputs If the Number of outputs parameter is a vector the number of output lines is equal to the number of elements in the vector The output signal widths depend on the inp
143. aracteristics When there are two points at a given input value the block generates output according to these rules e When u is less than zero the output is the value connected with the point first encountered when moving away from the origin in a negative direction In this example when u is 1 y is 2 marked with a solid circle When u is greater than zero the output is the value connected with the point first encountered when moving away from the origin in a positive direction In this example when u is 1 yis 2 marked with a solid circle When u is at the origin and there are two output values specified for zero input the actual output is their average In this example if there were no point at u O and y 1 the output would be 0 the average of the two points at u 0 If there are three points at zero the block generates the output associated with the middle point In this example the output at the origin is 1 The Look Up Table block icon displays a graph of the input vector versus the output vector When a parameter is changed on the block s dialog box the graph is automatically redrawn when you press the Apply or Close button Look Up Table Look Up Table Performs 1 D linear interpolation of input values using the specified table Extrapolation is performed outside the table boundaries The vector of values containing possible block input values This vector must be the same size as the output vector
144. aragraph c 1 ii of the Rights in Technical Data and Computer Software Clause at DFARS 252 227 7013 b for any other unit or agency NOTICE Notwithstanding any other lease or license agreement that may pertain to or accompany the delivery of the computer software and accompanying documentation the rights of the Government regarding its use reproduction and disclosure are as set forth in Clause 52 227 19 c 2 of the FAR Contractor manufacturer is The MathWorks Inc 24 Prime Park Way Natick MA 01760 1500 MATLAB Simulink Handle Graphics and Real Time Workshop are registered trademarks and Stateflow and Target Language Compiler are trademarks of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Printing History March 1992 May 1997 First printing Revised for 2 1 online version Reprints December 1993 November 1994 J une 1995 J uly 1996 Getting Started To the Reader ccccc cece eee eee 1 2 What Is Simulink 0 0 0 0 ees 1 2 How to Use This Manual 0 00 e eee eee ee 1 3 Professional Application Toolboxes 000eeeeeee 1 5 The Simulink Real Time Workshop 000000eeeees 1 10 Key Feat hes ee ee 1 10 The Real Time Workshop Ada Extension 00005 1 12 KOy PEUN ais chic cet cw aan oe Geli ane Medd oe Ra 1 12 Blocksets ccccec cece eee eee eee 1 14 The DSP Blockset 0 cece eee ees 1 14 The
145. arent system that contains the system you want to open The parent system s contents appear in the blocks list 2 Depending on whether the system is masked linked to a library block or has an open function callback you open it as follows If the system has no symbol to its left double click on its name or select its name and click on the Open System button If the system has an M or O before its name select the system name and click on the Look Into System button Looking into a Masked System or a Linked Block By default the Browser considers masked systems identified by M and linked blocks identified by L as blocks and not subsystems If you click on Open System while a masked system or linked block is selected the Browser displays the system or block s dialog box Open System works the same way as double clicking on the block in a block diagram Similarly if the block s OpenFcn callback parameter is defined clicking on Open System while that block is selected executes the callback function You can direct the Browser to look beyond the dialog box or callback function by selecting the block in the blocks list then clicking on Look Into System The Browser displays the underlying system or block Displaying List Contents Alphabetically By default the systems list indicates the hierarchy of the model Systems that contain systems are preceded with a plus sign When those systems are expanded the Browser d
146. arent icon Opaque Transparent Icon rotation When the block is rotated or flipped you can choose whether to rotate or flip theicon or tohaveit remain fixed in its original orientation The default is not to rotate the icon The icon rotation is consistent with block port rotation This figure shows the results of choosing Fixed and Rotates icon rotation when the AND gate block is rotated 5 Fixed Rotates 6 21 6 Using M asks to Customize Blocks Drawing coordinates This parameter controls the coordinate system used by the drawing commands This parameter applies only topl ot andtext drawing commands You can select from among these choices Autoscale Normalized and Pixel max X max Y 11 block width block height min X min Y 0 0 0 0 Autoscale Normalized Pixel e Autoscale automatically scales the icon within the block frame When the block is resized the icon is also resized F or example this figure shows the icon drawn using these vectors X 023 49 Y 4 6 35 8 The lower left corner of the block frame is 0 3 and the upper right corner is 9 8 The range of the x axis is 9 from 0 to 9 while the range of the y axis is 5 from 3 to 8 e Normalized draws theicon within a block frame whose bottom left corner is 0 0 and whose top right corner is 1 1 Only X and Y values between 0 and l appear When the block is resized theicon is alsoresized For example th
147. ation methods either from the Simulink menus or by entering commands in MATLAB s command window The menus are particularly convenient for interactive work while the command line approach is very useful for running a batch of simulations for example if you are doing Monte Carlo simulations or want to sweep a parameter across a range of values Using scopes and other display blocks you can see the simulation results while the simulation is running In addition you can change parameters and immediately see what happens for what if exploration The simulation results can be put in the MATLAB workspace for postprocessing and visualization Model analysis tools include linearization and trimming tools which can be accessed from the MATLAB command line plus the many tools in MATLAB and its application toolboxes And because MATLAB and Simulink are integrated you can simulate analyze and revise your models in either environment at any point How to Use This Manual Because Simulink is graphical and interactive we encourage you to jump right in and try it The manual contains eleven chapters and five appendices For a useful introduction that will help you start using Simulink quickly take a look at Running a Demo Model in Chapter 2 Browse around the model double click on blocks that look interesting and you will quickly get a sense of how Simulink works If you want a quick lesson in building a model see Building a Simp
148. ation Page Defining a Check Box Control A check box enables the user to choose between two alternatives by selecting or deselecting a check box This figure shows how the sample check box control was defined Prompt Show label Control type Checkbox gt Variable label Assignment Evaluate z The value of the variable associated with the parameter abel depends on whether the check box is selected and the Assignment type defined for the prompt Check box Evaluated Value Literal Value Checked 1 on Not checked 0 off Defining a Popup Control A popup enables the user to choose a parameter value from a list of possible values Y ou specify the list in the Popup strings field separating items with a vertical line This figure shows how the sample popup control was defined Prompt Color Control type Popup xl Variable color Assignment Evaluate Popup strings redlbluelgreenlyellow The value of the variable associated with the parameter co or depends on the item selected from the popup list and the Assignment type defined for the prompt Assignment Value Evaluate The index of the value selected from the list starting with 1 For example if the third item is selected the parameter value is 3 Literal A string that is the value selected If the third item is selected the parameter valueis green 6 13 6 Using M asks to Customize Blocks 6 14 Default Values
149. ation Parameters Dialog Box Ed Simulation parameters untitled BEI Solver Workspace 1 0 Diagnostics Simulation time Start time 0 0 Stop time 10 0 Solver options Type Yariable step M ode45 Dormand Prince x Max step size l auto Relative tolerance 1e 3 Initial step size auto Absolute tolerance 1e 6 Output options Refine output x Refine factor 1 Apply Revert Help Close Simulation Time You can changethestart time and stop time for the simulation by entering new values in the Start time and Stop time fields The default start time is 0 0 seconds and the default stop time is 10 0 seconds Simulation time and actual clock time are not the same F or example running a simulation for 10 seconds will usually not take 10 seconds The amount of time it takes to run a simulation depends on many factors including the model s complexity the solver s step sizes and the computer s clock speed Solvers Simulation of Simulink models involves the numerical integration of sets of ordinary differential equations ODEs Simulink provides a number of solvers for the simulation of such equations Because of the diversity of dynamic system behavior some solvers may be more efficient than others at solving a particular problem To obtain accurate and fast results take care when choosing the solver and setting parameters You can choose between variable step and fixed step solvers Variab
150. be scalar or vector valued e If theinput is a scalar the subsystem executes if the input value is greater than zero e If the input is a vector the subsystem executes if any of the vector elements is greater than zero For example if the control input signal is a sine wave the subsystem is alternately enabled and disabled as shown in this figure An up arrow signifies enable a down arrow disable Simulink uses the zero crossing slope method to determine whether an enable is to occur If the signal crosses zero and the slope is positive the subsystem is enabled If the slope is negative at the zero crossing the subsystem is disabled Creating an Enabled Subsystem You create an enabled subsystem by copying an Enable block from the Connections library into a subsystem Simulink adds an enable symbol and an enable control input port to the Subsystem block icon Subsystem 7 Conditionally Executed Subsystems 7 4 Setting Output Values while the Subsystem Is Disabled Although an enabled subsystem does not execute while it is disabled the output signal is still available to other blocks While an enabled subsystem is disabled you can choose to hold the subsystem outputs at their previous values or reset them to their initial conditions Open each Outport block s dialog box and select one of the choices for the Output when disabled parameter as shown in the dialog box below e Choose held to cause the output to
151. bjects finding 11 12 path 11 3 selecting morethan one 3 4 selecting one 3 4 odel solver 4 10 odel13 solver 4 9 hybrid systems 10 15 Memory block 4 19 9 97 odel5s solver 4 8 4 9 4 19 hybrid systems 10 15 maximum order 4 12 4 25 Memory block 4 19 9 97 unstable simulation results 4 20 ode2 solver 4 10 ode23 solver 4 9 hybrid systems 10 15 ode23s solver 4 9 4 12 4 20 ode3 solver 4 10 ode4 solver 4 9 ode45 solver 4 8 hybrid systems 10 15 ode5 solver 4 9 offset to sample time 10 11 offsets specifying in S functions 8 9 8 45 opaque icon 6 21 Open menu item 3 3 Open System menu item 3 43 open_system command 11 19 OpenFcn block callback parameter 3 31 opening block dialog boxes 2 9 3 7 11 19 Simulink block library 11 24 Subsystem block 3 29 system windows 11 19 operating point 5 9 Optimization Toolbox 1 8 options structure getting values 4 28 setting values 4 24 ordering of states 4 16 organization of manual 1 3 orientation of blocks 3 8 Outport block 9 103 example 5 2 in subsystem 3 28 3 29 9 141 linearization 5 4 i nmod function 5 9 output additional 4 12 between trigger events 7 10 disabled subsystem 7 4 displaying values of 9 57 enable signal 7 5 maximum rows 4 25 options 4 12 outside system 9 103 refine factor 4 26 saving to workspace 4 15 selected elements of input vector 9 128 S function 8 13 8 61 smoother 4 12 specifying for simulation 4 13 specifying points 4 26 switching between inputs 9 144 sw
152. block dialog box lets you output the enable control signal To output the control signal select the Show output port check box Enable Place this block in a subsystem to create an enabled r Enable Port subsystem Parameters States when enabling held it Select this check box to show the output port Apply Revert Help Close This feature allows you to pass the control signal down into the enabled subsystem which can be useful where logic within the enabled subsystem is dependent on the value or values contained in the control signal Blocks an Enabled Subsystem Can Contain An enabled subsystem can contain any block whether continuous or discrete Discrete blocks in an enabled subsystem execute only when the subsystem executes and only when their sample times are synchronized with the simulation sample time E nabled subsystems and the model use a common dock 7 Conditionally Executed Subsystems For example this system contains four discrete blocks and a control signal The discrete blocks are e Block A which has a sample time of 0 25 seconds e Block B which has a sample time of 0 5 seconds e Block C within the Enabled subsystem which has a sample time of 0 125 seconds e Block D alsowithin the Enabled subsystem which has a sampletime of 0 25 seconds The enable control signal is generated by a Pulse Generator block labeled Signal E which changes from 0 to
153. block generates normally distributed random numbers The seed is reset to the specified value each time a simulation starts By default the sequence produced has a mean of 0 and a variance of 1 although you can vary these parameters The sequence of numbers is repeatable and can be produced by any Random Number block with the same seed and parameters To generate a vector of random numbers with the same mean and variance specify the Initial seed parameter as a vector To generate uniformly distributed random numbers use the Uniform Random Number block described on page 9 158 Avoid integrating a random signal because solvers are meant to integrate relatively smooth signals Instead use the Band Limited White Noise block Random Number gt Random Number Outputs a normally Gaussian distributed random signal Output is repeatable for a given seed The mean of the random numbers The default is 0 Parameters Mean pan The variance of the random numbers The R default is 1 1 The starting seed for the random number generator The default is 0 Initial seed 0 Sample time z 0 Thetime interval between samples The default is 0 causing the block to have continuous sample Apply Revert Help time Sample Time Continuous or discrete Scalar Expansion Of parameters Vectorized Yes Zero Crossing No 9 111 Random Number 9 112 Rate Limiter Purpose Limit the rate of change of
154. bs no block specific parameters Algebraic Constraint Al gebraic Constraint masked Backlash Back ash BacklashWidth Deadband width scalar or vector 1 Initial Out put Initial output scalar or vector 0 Combinatorial Logic Combi nat ori al Logic TruthTable Truth table matrix 0 0 0 1 0 1 1 0 0 1 1 0 1 0 1 1 Coulomb amp Viscous Friction Coul ombic and Viscous Friction masked Dead Zone DeadZone LowerValue Start of dead zone scalar or vector 0 5 UpperVal ue End of dead zone scalar or vector 0 5 Elementary Math El ement ary Math Operator Operator sin cos tan asin acos atan atan2 sinh cosh tanh exp log logl0 floor ceil sqrt reciprocal pow hypot Fon Fen Expn Expression expression sin u 1 exp 2 3 u 2 Hit Crossing Hit Cross Hit CrossingOffset Hit crossing offset scalar or vector 0 Hit CrossingDirection Hit crossing direction rising falling either ShowOut put Port Show output port on off Logical Operator Logic A 16 Block Specific Parameters Table A 6 Nonlinear Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Operator Operator AND OR NAND NOR XOR NOT Inputs Number of input ports scalar 2 Look up Table Lookup Input Values Out put Val ues Look Up Table 2 D Lookup Table Rowl ndex Col umn ndex Out put Val ues Math Function Mat h Operator MATLAB Fon
155. bsystem block and choose Mask Subsystem from the Edit menu The mask dialog box shown above is created largely on the Initialization page of the Mask Editor For this sample model the page looks like this EJ Mask Editor samplemask mx b Of x Documentation Mask type SampleMaskedBlock Type Variable Icon Initialization Prompt Add Parameter fields prompts types Intercept and variables that hold the Delete lt lt end of parameter list gt gt values entered by the mode user u Down af E J Prompt Slope Control type Edit Assignment Evaluate Where you enter and edit the Variable m parameter field characteristics Initialization commands The commands that define variables used by the icon drawingcommand or by blocksin the masked subsystem Apply Revert Unmask Help Close A Sample M asked Subsystem The Mask Editor enables you to specify these attributes of a mask parameter e The prompt the text label that describes the parameter e The control type the style of user interface control that determines how parameter values are entered or selected e The variable the name of the variable that will store the parameter value Generally it is convenient to refer to masked parameters by their prompts In this example the parameter associated with slope is referred to as the Slope parameter and the parameter associated
156. calar output width is equal to the number of rows in the numerator The Discrete Transfer Fcn block represents the method typically used by control engineers representing discrete systems as polynomials in z The Discrete Filter block represents the method typically used by signal processing engineers who describe digital filters using polynomials in z the delay operator The two methods are identical when the numerator is the same length as the denominator The Discrete Transfer Fcn block displays the numerator and denominator within its icon depending on how they are specified See the description of the Transfer F cn block on page 9 151 for more information Discrete Transfer Fcn Parameters and Dialog Box Characteristics Discrete Transfer Fen r Discrete Transfer Fen Matrix expression for numerator vector expression for denominator Output width equals the number of rows in the numerator Coefficients are for descending powers of z Parameters Numerator 1 Denominator 1 0 5 Sample time 1 Apply Revert Help The row vector of numerator coefficients A matrix with multiple rows can be specified to generate multiple output The default is 1 Therow vector of denominator coefficients The default is 1 0 5 The time interval between samples The default is 1 Direct Feedthrough Only if the lengths of the Numerator and Denominator parameters are equal Sample T
157. ccurate to within 0 1 e Absolute tolerance is a threshold error value This tolerance represents the acceptable error as the value of the measured state approaches zero The error for thei th state e is required to satisfy atol lt max rtol x x The figure below shows a plot of a state and the regions in which the acceptable error is determined by the relative tolerance and the absolute tolerance gt rtol x Region in which rtol determines acceptable error State_ Region in which atol determines acceptable error an Time 4 You might have to run a simulation more than once to determine an appropriate value for the absolute tolerance If the magnitudes of the states vary widely it might be appropriate to specify different absolute tolerance values for different states You can dothis on the Integrator block s dialog box 4 11 4 Running a Simulation 4 12 The Maximum Order for odel5s Theodel5s solver is based on NDF formulas of order one through five Although the higher order formulas are more accurate they are less stable If your model is stiff and requires more stability reduce the maximum order to 2 the highest order for which the NDF formula is A stable When you choose the odel5s solver the dialog box displays this parameter Asan alternative you might try using theode23s solver which is a fixed step lower order and A stable solver O ut
158. ce Reads time and output values from specified matrix in MATLAB s workspace The matrix must contain time values in column one Additional columns correspond to output elements Interpolates between rows The matrix from which time and data values are Parameters read If these values are not in the same matrix am table specify the time column vector T and data matrix U as T U 1f the values arein the same matrix specify the matrix name Avoid usingans to specify the data Apply Revert Help Sample Time Inherited from driven block Scalar Expansion No Vectorized Yes Zero Crossing No 9 69 Gain Purpose Library Description gt Parameters and Dialog Box Characteristics 9 70 Multiply block input Linear The Gain block generates its output by multiplying its input by a specified constant variable or expression The gain can bea scalar or vector which you can enter as a numeric value or as a variable or expression To multiply the input by a matrix use the Matrix Gain block described on page 9 96 The Gain block icon displays the value entered in the Gain parameter field if the block is large enough If the gain is specified as a variable the block displays the variable name although if the variable is specified in parentheses the block evaluates the variable each timethe block is redrawn and displays its value If the Gain parameter value is too long to be displayed in the b
159. changes toa double cross hairs EH H gt Constant Gain Release the mouse button Simulink replaces the port symbols by a connecting line with an arrow showing the direction of the signal flow You can create lines either from output to input or from input to output The arrow is drawn at the appropriate input port and the signal is the same gt Constant Gain Simulink draws connecting lines using horizontal and vertical line segments To draw a diagonal line hold down the Shift key while drawing the line 3 17 3 Creating a M odel 3 18 Drawing a Branch Line A branch lineis a line that starts from an existing line and carries its signal to the input port of a block Both the existing line and the branch line carry the same signal Using branch lines enables you to cause one signal to be carried to more than one block In this example the output of the Product block goes to both the Scope block and the To Workspace block Product To Workspace To add a branch line follow these steps 1 Position the pointer on the line where you want the branch line to start 2 While holding down the Ctrl key on a Microsoft Windows or X Windows system or the Option key on a Macintosh press and hold down the mouse button 3 Dragthe pointer totheinput port of thetarget block then release the mouse button and the Ctrl or Option key On a Microsoft Windows or X Windows system you can also use the right mouse but
160. ck and feeding the output of the block back into this state input Combinatorial Logic Combinatorial Logic Looks up the elements of the input vector treated as boolean values in the truth table and outputs the corresponding row of the Truth table parameter The input side of the truth table is implicit Parameters Truth table 0 0 0 1 0 1 1 0 0 1 1 0 1 0 1 1 The matrix of outputs Each column corresponds to an element of the output vector and each row corresponds to a row of the truth table Apply Revert Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion No Vectori zed Yes the output width is the number of columns of the Truth table parameter Zero Crossing No Constant Purpose Library Description i Parameters and Dialog Box Characteristics Generate a constant value Sources The Constant block generates a specified value independent of time The block generates one output which can be scalar or vector depending on the length of the Constant value parameter The block icon displays the specified value or values r Constant Outputs a constant Parameters Constant value 1 Apply Revert Help The output of the block If a vector the output is a vector of constants with the specified values The default value is 1 Sample Time Constant Scalar Expansion No Vectorized Yes Zero Crossing No
161. ck inputs are less than the first or greater than the last row or column parameter values the block extrapolates from the first two or last two points If either the Row or Column parameter has a repeating value the block chooses a value using the technique described for the Look Up Table block The Look Up Table block allows you to map a single input value into a vector of output values That block is described on page 9 87 Example In this example the block parameters are defined as Row 12 Col umn 3 4 Table 10 20 30 40 Thefirst figure shows the block outputting a value at the intersection of block inputs that match row and column values The first input is 1 and the second 9 89 Look Up Table 2 D input is 4 These values select the table value at the intersection of thefirst row row parameter value 1 and second column column parameter value 4 3 4 1 10 20 ook U Displa 2 30 40 Column a ed In the second figure the first input is 1 7 and the second is 3 4 These values cause the block tointerpolate between row and column values as shown in the table at the left The value at the intersection 28 is the output value 3134 4 110 14 20 1 7 24 28 34 Display Column Table 2 D 2 30 34 40 Parameters Look Up Table 2 D a nd Di a lo g ass Webs el mask etforms 2 D linear interpolation of input values using the Box specified input output
162. con Initialization Mask type SampleMaskedBlock m SampleMaskedBlock mask Models the equation for a line y mx b The slope and intercept are mask block parameters Block description Models the equation for a line y mx b The slope and intercept are mask block parameters Parameters Slope 3 Block help Enter the slope m and intercept b in the block dialog box parameter fields The block generates y for a given input x Intercept 2 Apply Fever gt Help Apply Revert Unmask Help Close Creating the Block Icon So far a customized dialog box has been created for themx b subsystem However the Subsystem block still displays the generic Simulink subsystem icon An appropriate icon for this masked block is a plot that indicates the slope of the line For a slope of 3 that icon looks like this 7 A Sample M asked Subsystem The block icon is defined on the Icon page For this block the Icon page looks like this EJ Mask Editor samplemask mx b 1 15 x Icon Initialization Documentation Mask type SampleMaskedBlock Drawing commands plot 0 1 0 m m lt 0 Drawing commands Icon frame visible Icon transparency Opaque Icon rotation Fined Drawing coordinates Nomaized Apply Revert Unmask Help Close Thedrawing command plots a linefrom 0 0 to
163. crete system can be found by using thebode command An Advanced Form of Linearization Thel i nmod2 routine provides an advanced form of linearization This routine takes longer to run than i nmod but may produce more accurate results The calling syntax for i nmod2 is similar to that used for i nmod but functions differently For instance i nmod2 sys x u produces a linear model as does i nmod however the perturbation levels for each state space matrix element are set individually to attempt to minimize roundoff and truncation errors i nmod2 tries to balance roundoff error caused by small perturbation levels which cause errors associated with finite precision mathematics and truncation error caused by large perturbation levels which invalidate the piecewise linear approximation With the form A B C D linmod2 sys x u pert thevariablepert indicates the lowest level of perturbation that can be used the default is 1e8 i nmod2 has the advantage that it can detect discontinuities and produce warning messages such as the following Warning discontinuity detected at A 2 3 When such a warning occurs try a different operating point at which to obtain the linear model With the form A B C D linmod2 sys x u pert Apert Bpert Cpert Dpert the variablesApert Bpert Cpert andDpert are matrices used to set the perturbation levels for each state and input combination therefore thei j th 5 11 Lin
164. ctions 0 0 00 eee eee 8 15 Passing Additional Parameters 0 cece eee eee 8 25 Writing S Functions as C MEX Files 0000eeeues 8 26 Statements Required at the Top of the File 8 27 Statements Required at the Bottom of the File 8 27 vi Contents Defining S Function Block Characteristics 8 28 A Simple C MEX File Example 20000 eee eae 8 29 Examples of C MEX File S Function Blocks 8 32 Creating General Purpose S Function Blocks 8 42 Specifying Parameter Values Interactively 8 43 Output and Work Vector Widths 0 0 0 c eee eee 8 51 Removing Ports When No Inputs and or Outputs 8 51 Using Function Call Subsystems 0000 ee eee 8 51 Instantaneous Update of S Function Inputs 8 53 Exception Handling 0 cece tees 8 53 Error H ndlind u ee een 8 54 Normal or Real Time Workshop Simulation 8 54 Additional Macros in mdli nitializeSizes 8 54 Block Reference 9 What Each Block Reference Page Contains 0 0 9 2 The Simulink Block Libraries sasasasssssassassanann 9 3 10 How Simulink Works zzsnunnunnnnonnnun nun nn nun 10 2 ZErO CrOssiNgS nase dae arme 10 3 Algebraic LOopS 22H2e rennen nennen 10 7 Invariant Constants 0 000 seen eee 10 9 Discrete Time Systems 0 c0cee eee e eee 10
165. d scalar sample period 1 or vector period offset variable si mout scalar inf scalar 1 scalar sample period 1 or vector period offset Table A 8 Sources Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Band Limited White Noise Continuous White Noise masked Chirp Signal chi r p masked Clock Cl ock no block specific parameters Constant Constant Value Constant value Digital Clock Di git al Cl ock Sampl eTi me Sample time From File Fr omFi e Fil eName Filename From Workspace Fr omWorks pace scalar or vector 1 scalar Sample period 1 or vector period offset filename untitled mat A 21 A Model and Block Parameters Table A 8 Sources Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Variabl eName Matrix table Pulse Generator Pulse Generator masked Ramp Ramp masked Random Number RandomNumber Seed Repeating Sequence Repeating table masked Initial seed Signal Generator Si gnal Generator Wave Amp Freq Uni Form itude uency S Sine Wave Si n Amp Freq Phas Samp itude uency e eTi me Step Step Ti me Befo Afte re r Wave form Amplitude Frequency Units Amplitude Frequency Phase Sample time Step time Initial value Final value matrix T U
166. d icon look like this The mask dialog box r SampleMaskedBlock mask Models the equation for a line y mx b The slope and intercept are mask block parameters Parameters Slope 3 The block icon Intercept Apply Revert Help The user of this subsystem enters values for Slope and Intercept into the mask dialog box Simulink makes these values available to all the blocks in the underlying subsystem Masking this subsystem creates a self contained functional unit with its own application specific parameters Slope and Intercept The mask maps these mask parameters to the generic parameters of the underlying blocks The complexity of the subsystem is encapsulated by a new interface that has the look and feel of a built in Simulink block 6 3 6 Using M asks to Customize Blocks Creating a mask for this subsystem involves these tasks Specifying the prompts for the mask dialog box parameters In this example the mask dialog box has prompts for the slope and intercept Specifying the variable name used to store the value of each parameter Entering the documentation of the block consisting of the block description and the block help text Specifying the drawing command that creates the block icon Specifying the commands that provide the variables needed by the drawing command there are none in this example Creating Mask Dialog Box Prompts To create the mask for this subsystem select the Su
167. defined in old_opstruct si met with noinput arguments displays all property names and their possible values You cannot obtain or set values of these properties and parameters using the get_paramandset_param commands AbsTol positive scalar le 6 Absolute error tolerance This scalar applies to all elements of the state vector AbsTol applies only to the variable step solvers Decimation positive integer 1 Decimation for output variables Decimation factor applied to the return variablest x andy A decimation factor of 1 returns every data logging time point a decimation factor of 2 returns every other data logging time point etc simset Dst Workspace base current parent Where to assign variables This property specifies the workspace in which to assign any variables defined as return variables or as output variables on the To Workspace block Final Stat eName string Name of final states variable This property specifies the name of a variable into which Simulink saves the model s states at the end of the simulation FixedStep positive scalar Fixed step size This property applies only tothe fixed step solvers If the model contains discrete components the default is the fundamental sample time otherwise the default is onefiftieth of the simulation interval InitialState vector Initial continuous and discrete states The initial state vector consists ofthe continuous states if any followed
168. definesthe data store For moreinformation see page 9 25 Thesize of the data storeis set by the Data StoreM emory block that defines and initializes the data store Each Data Store Write block that writes to that data store must write the same amount of data More than one Data Store Write block can write to the same data store However if two Data Store Write blocks attempt to write to the same data store at the same simulation step results are unpredictable Data Store Write r Data Store Write Writes values to specified data store r Parameters The name of the data store to which this block writes data Data store name A Sample time The sample time which controls when the block writes tothe data store The default 1 indicates Apply Revert Help that the sample time is inherited Sample Time Continuous or discrete Vectorized Yes 9 27 Dead Zone Purpose Provide a region of zero output Library Nonlinear Description The Dead Zone block generates zero output within a specified region called its dead zone The lower and upper limits of the dead zone are specified as the Start of dead zone and End of dead zone parameters The block output depends on the input and dead zone e If theinput is within the dead zone greater than the lower limit and less than the upper limit the output is zero e If theinput is greater than or equal tothe upper limit the output is theinput minus the uppe
169. described later in this chapter Torun Simulink and work with your model select commands from the Simulink menus or enter them in the MATLAB command window e Microsoft Windows and X Windows a Simulink menu bar appears near the top of each model window The menu commands apply tothe contents of that window e Macintosh the Simulink menu bar appears at the top of the desktop The menu commands apply to the contents of the active window When you run a simulation and analyze its results you can enter MATLAB commands in the MATLAB command window Running a simulation is discussed in Chapter 4 and analyzing simulation results is discussed in Chapter 5 Starting Simulink Simulink Windows Simulink uses separate windows to display a block library a model and graphical scope simulation output These windows are not MATLAB figure windows and cannot be manipulated using Handle Graphics commands Simulink windows are sized to accommodate the most common screen resolutions available If you have a monitor with exceptionally high or low resolution you may find the window sizes too small or too large If this is the case resize the window and save the model to preserve the new window dimensions Creating a New Model To create a new model choose New from the File menu and select Model or click on the Simulink icon on the MATLAB toolbar You can move the window as you do other windows Chapter 2 describes how to build a simple mode
170. detail in Chapter 4 Examples showing how to change parameters follow the table Parameter values must be specified as quoted strings The string contents depend on the parameter and can be numeric scalar vector or matrix a variable name a filename or a particular value The Values column shows the type of value required the possible values Separated with a vertical line and the default value enclosed in braces Table A 1 Model Parameters Parameter Description Values Name Model name text Version Simulink version used to modify the release model read only Si mParamPage Simulation Parameters dialog box Solver Workspacel 0O page to display page last displayed Di agnostics Samp eTi meCol ors Sample Time Colors menu option on off InvariantConstants Invariant constant setting on off Wi deVectorlines Wide Vector Lines menu option on off ShowLineWidths Show Line Widths menu option on off PaperOrientation Printing paper orientation portrait landscape PaperType Printing paper type usletter uslegal a3 a4 a5 b4 tabloid PaperUnits Printing paper size units normalized inches centimeters points StartTi me Simulation start time scalar 0 0 A 3 A Model and Block Parameters Table A 1 Model Parameters Continued Parameter Description Values StopTi me Simulation stop time scalar 10 0 Sol ver Solver ode45 ode23 odell3 odel5s ode23s ode5 ode4 ode
171. dvantage of MATLAB s open system approach You can inspect M files add to them or usethem for templates when creating your own functions e Every toolbox is available on any computer platform that runs MATLAB Hereis a list of professional toolboxes currently available from The MathWorks This list is by no means static more are being created every year The Communications Toolbox The Communications Toolbox provides an integrated set of tools for accelerating the design analysis and simulation of modern communications systems It combines MATLAB s high level language with the ease of use of Simulink s block diagram interface and provides communications engineers with comprehensive communications system design and analysis capabilities The toolbox is useful in such diverse industries as telecommunications telephony aerospace and computer peripherals 1 G etting Started 1 6 The Control System Toolbox The Control System Toolbox the foundation of the MATLAB control design toolbox family contains functions for modeling analyzing and designing automatic control systems The application of automatic control grows each year as sensors and computers become less expensive As a result automatic controllers are used not only in highly technical settings for automotive and aerospace systems computer peripherals and process control but also in less obvious applications such as washing machines and cameras The Financial To
172. e default decimation 1 displays data at every time step The Sample time parameter enables you to specify a sampling interval at which to display points This parameter is useful when using a variable step solver where the interval between time steps may not be the same The default value of 1 causes the block to ignore sampling interval when determining which points to display If the block input is a vector you can resize the block to show more than just the first element You can resize the block vertically or horizontally the block adds display fields in the appropriate direction A black triangle indicates that the block is not displaying all input vector elements F or example the figure below shows a model that passes a vector to a Display block The top model 9 57 Display Parameters and Dialog Box Characteristics 9 58 shows the block before it is resized notice the black triangle The bottom model shows the resized block displaying both input elements Displays only one element of input vector but indicates Display there are more p Fa Displays both elements ux of input vector Mux Constant Display Display r Display Numeric display of input values The format of the data displayed The default is Short r Parameters Format How often to display data The default value 1 displays every input point Decimation 1 T Floating display If checked
173. e from the first input the fifth element comes from the second input and the sixth and seventh elements come from the third input If it is not important that these inputs have fixed widths you could specify the Number of inputs as 3 To specify three inputs where the first input vector must have four elements you could specify 4 1 1 Simulink determines the widths of the second and third inputs and sizes the output width accordingly Simulink draws the M ux block with the specified number of inputs If you change the number of input ports Simulink adds or removes them from the bottom of the block icon Using a Variable to Provide the Number of Inputs Parameter When you specify the Number of inputs parameter as a variable Simulink issues an error message if the variable is undefined in the workspace 9 101 Mux Parameters H r Mux a nd Dia log Combine scalar or vector signals into larger vectors Box Parameters Number of inputs n x 3 Thenumber and width of inputs The total of the input widths must match the width of the output Apply Revert Help line Characteristics SampleTime Inherited from driving block s Vectorized Yes 9 102 Outport Purpose Library Description gt Create an output port for a subsystem or an external output Connections Outports are the links from a system to a destination outside the system Simulink assigns Outport block port numbers according to
174. e middle Zoom toolbar button Define the zoom region by positioning the pointer at one end of the region pressing and holding down the mouse button then moving the pointer Scope to the other end of the region This figure shows the Scope after defining the zoom region but before releasing the mouse button Ed vdp Scope LIP A Alta 2 Zoom in x direction 1 Time offset 0 When you release the mouse button the Scope displays the magnified region Zooming in the y direction works the same way except that you press the right most Zoom toolbar button before defining the zoom region Saving the Axes Settings The Save axes settings toolbar button enables you to store the current x and y axis settings so you can apply them to the next simulation the Save axes settings button You might want to do this after zooming in on a region of the displayed data so you can see the same region in another simulation The time range is inferred from the current x axis limits You can also change axes limits by choosing the Properties toolbar button the Properties button 9 125 Scope 9 126 When you click on the Properties button this dialog box appears EJ Properties Scope x Axes Settings Default limits Y max 5 Time range auto Y min 5 T Hide tick labels The dialog box has two tabs Axes and Settings You apply the current axes limits by clicking on the Apply or Close button
175. e model is loaded Defining a callback routine for this parameter might be useful for generating an interface that requires that the model has already been loaded Post SaveFcn After the model is saved PreLoadFcn Before the model is loaded Defining a callback routine for this parameter might be useful for loading variables used by the model PreSaveFcn Before the model is saved StartFen Beforethesimulation starts StopFen After thesimulation stops Output is written to workspace variables and files beforetheStopFen is executed 3 30 Creating Subsystems Table 3 2 Block Callback Parameters Parameter When Executed CloseFcn When the block is closed using thec ose_ system command CopyFen After a block is copied The callback is recursive for Subsystem blocks that is if you copy a Subsystem block that contains a block for which theCopyFen parameter is defined the routine is also executed The routine is also executed if an add_ bl ock command is used to copy the block DeleteFcn Before a block is deleted This callback is recursive for Subsystem blocks InitFen Before the block diagram is compiled and before block parameters are evaluated LoadFen After the block diagram is loaded This callback is recursive for Subsystem Model CloseFcn NameChangeFcn OpenFcn ParentCloseFcn PreSaveFcn PostSaveFcn blocks Before the block diagram is closed This callback is recursive for Subsystem blocks A
176. e next figure shows the state of the block when the input has reached the end of the deadband and engaged the output The output remains at its previous value 1 0 0 5 0 0 5 1 0 Input reaches end of deadband engaged Thefinal figure shows how a change in input affects the output while they are engaged 1 0 0 5 0 0 5 1 0 Fr Input moves in positive direction Output Input deadband width 2 If the input reverses its direction it disengages from the output The output remains constant until the input either reaches the opposite end of the deadband or reverses its direction again and engages at the same end of the deadband Now as before movement in the input causes equal movement in the output For example if the deadband width is 2 and the initial output is 5 the output y at the start of the simulation is e 5if theinput u is between 4 and 6 eutlifu lt 4 eu lifu gt 6 9 13 Backlash 9 14 This sample model and the plot that follows it show the effect of a sine wave passing through a Backlash block simout Sine Wave Mux To Workspace The Backlash block parameters are unchanged from their default values the deadband width is 1 and the initial output is 0 Noticein the plotted output below that the Backlash block output is zero until the input reaches the end of the deadband at 0 5 Now the input and output are engaged and the output moves as the input does until the input changes direc
177. e preset to zero If you need to specify initial conditions convert to state space form usingt f 2ss and use the State Space block The tf2ss utility provides the A B C and D matrices for the system For more information typehel p tf2ss or consult the Control System Toolbox U ser s Guide The Transfer Fcn Block Icon The numerator and denominator are displayed on the Transfer Fcn block icon depending on how they are specified e f each is specified as an expression a vector or a variable enclosed in parentheses the icon shows the transfer function with the specified coefficients and powers of s If you specify a variable in parentheses the variableis evaluated For example if you specify Numerator as 3 2 1 and 9 151 Transfer Fcn Denominator as den whereden iS 7 5 3 1 the block icon looks like this 38242841 7st48s2435 1 e If each is specified as a variable the icon shows the variable name followed by s For example if you specify Numerator as num and Denominator as den the block icon looks like this num s den si Parameters and Dialo g Matrix expression for numerator vector expression for Box denominator Output width equals the number of rows in the numerator Coefficients are for descending powers of s Transfer Fen r Transfer Fen The row vector of numerator coefficients A reo matrix with multiple rows can be specified to m i generate multiple output
178. e real problems knowledge of this tool will serve you well throughout your professional career We hope you enjoy exploring the software What Is Simulink Simulink is a software package for modeling simulating and analyzing dynamical systems It supports linear and nonlinear systems modeled in continuous time sampled time or a hybrid of the two Systems can be also multirate i e have different parts that are sampled or updated at different rates For modeling Simulink provides a graphical user interface GUI for building models as block diagrams using click and drag mouse operations With this interface you can draw the models just as you would with pencil and paper or as most textbooks depict them This is a far cry from previous simulation packages that require you to formulate differential equations and difference equations in a language or program Simulink includes a comprehensive block To the Reader library of sinks sources linear and nonlinear components and connectors Y ou can also customize and create your own blocks Models are hierarchical so you can build models using both top down and bottom up approaches You can view the system at a high level then double click on blocks to go down through the levels to see increasing levels of model detail This approach provides insight into how a model is organized and how its parts interact After you define a model you can simulate it using a choice of integr
179. e same For example this statement obtains the values of the initial conditions and the ordering of the states for thevdp model the example shows only the values for sizes 1 the number of continuous states and si zes 2 the number of discrete states sizes x0 xstord vdp 0 sizes xstord vdp Integratorl vdp Integrator2 The Simulation Parameters Dialog Box The Diagnostics Page You can indicate the desired action for many types of events or conditions that can be encountered during a simulation by selecting the Diagnostics tab on the Simulation Parameters dialog box This dialog box appears Ed Simulation parameters untitled BEI Salver Workspace 1 0 Diagnostics Events Action Min step size violation Warning None Unconnected block input Warning i Unconnected block output Warning Unconnected line Warning Error Algebraic loop Warning z Debugging Consistency checking ot I Disable zero crossing detection Apply Revert Help f For each event type you can choose whether you want no message a warning message or an error message A warning message does not terminate a simulation but an error message does Consistency Checking Consistency checking is a debugging tool that validates certain assumptions made by Simulink s ODE solvers Its main useisto make surethat S functions adhere to the same rules as Simulink built in blocks Because con
180. e same model Using Data Saved by a To File or a To Workspace Block The From File block can read data written by a To File block without any modifications To read data written by a To Workspace block and saved toa file e Thedata must include the simulation times The easiest way to include time data in the simulation output is to specify a variable for time on the Workspace 1 O page of the Simulation Parameters dialog box See Chapter 4 for more information e The form of the data as it is written to the workspace is different from the form expected by the From File block Before saving the data toa file transpose it When it is read by the From File block it will bein the correct form From File Reads time and output values from the first matrix in the specified MAT file The matrix must contain time values in tow one Additional rows correspond to output elements Interpolates between columns Parameters File name 2 The name of the file that contains the data used untitled mat as input The default filenameisuntitl ed mat Apply Revert Help i Sample Time Inherited from driven block Scalar Expansion No Vectorized Yes Zero Crossing No 9 67 From Workspace 9 68 Purpose Library Description Read data from a matrix defined in the workspace Sources The From Workspace block reads data from a matrix in the workspace The block icon displays the name of the matrix or its time and inp
181. e solution Also if your model contains periodic or nearly periodic behavior and you know the period set the maximum step size to some fraction such as 1 4 of that period In general for more output points change the refine factor not the maximum step size For more information see Refine Factor on page 4 12 The Simulation Parameters Dialog Box Initial step size By default the solvers select an initial step size by examining the derivatives of the states at the start time If the first step size is too large the solver may step over important behavior The initial step size parameter is a suggested first step size The solver tries this step size but reduces it if error criteria are not satisfied Error Tolerances The solvers use standard local error control techniques to monitor the error at each time step During each time step the solvers compute the state values at the end of the step and also determine the local error the estimated error of these state values They then compare the local error to the acceptable error which is a function of the relative tolerance rtol and absolute tolerance atol If the error is greater than the acceptable error for any state the sol ver reduces the step size and tries again e Relative tolerance measures the error relative to the size of each state The relative tolerance represents a percentage of the state s value The default le 3 means that the computed state will be a
182. e states initial conditions from the Initial condition parameter if set tointernal or from an external block if set to external The states initial conditions Set the Initial condition source parameter value to internal If checked limits the states to a value between the Lower saturation limit and Upper saturation limit parameters The upper limit for the integral The default is inf The lower limit for the integral The default is inf If checked adds a saturation output port to the block If checked adds an output port to the block for the block s state Absolute tolerance for the block s states Direct Feedthrough Yes of the reset and external initial condition source ports Sample Time Continuous Scalar Expansion Of parameters States Inherited from driving block or parameter Vectorized Yes Zero Crossing If the Limit output option is selected one for detecting reset one each to detect upper and lower saturation limits one when leaving saturation Logical Operator Purpose Library Description mo Parameters and Dialog Box Perform the specified logical operation on the input Nonlinear The Logical Operator block performs any of these logical operations on its inputs AND OR NAND NOR XOR and NOT A nonzeroinput is treated as TRUE 1 azeroinput as FALSE 0 The output depends on the number of inputs their vector size and the selected operator The output is1 if TRUE and 0
183. earization Analysis 5 12 Notes element of Apert is the perturbation level associated with obtaining thei th element of theA matrix Return default perturbation sizes with A B C D Apert Bpert Cpert Dpert linmod2 sys x u By default the system time is set to zero For systems that are dependent on time you can set the variablepert to atwo element vector where the second element is used to set the value oft at which to obtain the linear model When the model being linearized is itself a linear model the problem of truncation error no longer exists therefore you can set the perturbation levels to whatever value is desired A relatively high value is generally preferable since this tends to reduce roundoff error The operating point used does not affect the linear mode obtained The ordering of the states from the nonlinear model to the linear model is maintained For Simulink systems a string variable that contains the block name associated with each state can be obtained using sizes x0 xstring sys wherexst ring isa vector of strings whosei th row is the block name associated with thei th state Inputs and outputs are numbered sequentially on the diagram For single input multi output systems you can convert to transfer function form using the routiness2tf or to zero pole form using ss2zp You can also convert the linearized models to LTI objects using ss This function produces an LTI object in state sp
184. eb Command and masked block help 6 25 zooming in on displayed data 9 123 white noise generating 9 16 Wide Vector Lines menu item 3 11 Width block 9 162 work vectors 8 48 8 56 workspace destination 4 25 loading from 4 14 mask 6 5 6 14 reading data from 9 68 saving to 4 15 source 4 26 writing output to 9 148 writing to 4 5 Workspace I O page of Simulation Parameters di alog box 4 14 writing data to data store 9 27 output to file 9 146 output to workspace 9 148 x XY Graph block 9 163 Z zero crossings 10 3 10 6 detecting 4 27 9 75 disabling detection of 4 18 zero output in region generating 9 28 zero crossing slope method 7 3 Zero Order Hold block 9 159 9 164 compared to First Order Hold block 9 63 Zero Pole block 9 165
185. ected block is displayed choose a menu item from the Format menu e TheHide Name menu item hides a visible block name When you select Hide Name it changes to Show Name when that block is selected e The Show Name menu item shows a hidden block name Disconnecting Blocks To disconnect a block from its connecting lines hold down the Shift key then drag the block to a new location Blocks Vector Input and Output Almost all Simulink blocks accept scalar or vector inputs generate scalar or vector outputs and allow you to provide scalar or vector parameters These blocks are referred toin this manual as being vectorized You can determine which lines in a model carry vector signals by choosing Wide Vector Lines from the Format menu When this option is selected lines that carry vectors are drawn thicker than lines that carry scalars The figures in the next section show scalar and vector lines If you change your model after choosing Wide Vector Lines you must explicitly update the display by choosing Update Diagram from the Edit menu Starting the simulation also updates the block diagram display Block descriptions in Chapter 9 discuss the characteristics of block inputs outputs and parameters Scalar Expansion of Inputs and Parameters Scalar expansion is the conversion of a scalar value into a vector of identical elements Simulink applies scalar expansion to inputs and or parameters for most blocks Block descriptio
186. ector of outputs y and a vector of states x x u tat y input rate output The state vector may consist of continuous states discrete states or a combination of both The mathematical relationships between these quantities are expressed by these equations y f t x U output Xa fu t x u update x fy t x u derivative Xe where x Xq k Simulation consists of two phases initialization and simulation During the initialization phase 1 The block parameters are passed to MATLAB for evaluation The resulting numerical values are used as the actual block parameters 2 Themodel hierarchy is flattened Each subsystem that is not a conditionally executed subsystem is replaced by the blocks it contains 3 Blocks are sorted into the order in which they need to be updated The sorting algorithm constructs a list such that any block with direct feedthrough is not updated until the blocks driving its inputs are updated It is during this step that algebraic loops are detected For more information about algebraic loops see page 10 7 4 Theconnections between blocks are checked to ensure that the vector length of the output of each block is the same as the input expected by the blocks it drives Now the simulation is ready to run A model is simulated using numerical integration Each of the supplied ODE solvers simulation methods depends on the ability of the model to provide the derivatives of its continuous states
187. ed function or expression is applied to the input The output of the function must match the output width of the block or an error occurs Here are some sample valid expressions for this block sin atan2 u u 1 u 1 u 2 2 NOTE This block is slower than the Fcn block because it calls the MATLAB parser during each integration step Consider using built in blocks such as the Fcn block or the Math Function block instead or writing the function as an M file or ME X file S function then accessing it using the S F unction block MATLAB Fen MATLAB Fen Passes the input values to a MATLAB function for evaluation The function must return a single vector argument of length Output width Examples sin sin u foo u 1 u 2 The function or expression If you specify a function only it is not necessary to indude the Parameters input argument in parentheses MATLAB function sin The output width If the output width is to bethe same as the input width specify 1 Otherwise you must specify the correct width or an error will result Output width 1 Apply Revert Help MATLAB Fcn Characteristics Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving block N A Yes No 9 95 Matrix Gain Purpose Multiply the input by a matrix Library Linear Description The Matrix Gain block implements a matrix gain It gen
188. efault is 1 The minimum y axis value The default is 1 The maximum y axis value The default is 1 The time interval between samples The default is 1 which means that the sample time is determined by the driving block Inherited from driving block 0 9 163 Zero Order Hold Purpose Library Description Mm Parameters and Dialog Box Characteristics 9 164 Implement zero order hold of one sample period Discrete The Zero Order Hold block implements a sample and hold function operating at the specified sampling rate The block accepts one input and generates one output both of which can be scalar or vector This block provides a mechanism for discretizing one or more signals or resampling the signal at a different rate You can use it in instances where you need to model sampling without requiring one of the other more complex discrete function blocks For example it could be used in conjunction with a Quantizer block to model an A D converter with an input amplifier Zero Order Hold Zero Order Hold Zero order hold r Parameters Sample time Apply Revert Help Direct Feedthrough Yes The time interval between samples The default isl Sample Time Discrete Scalar Expansion Yes States 0 Vectorized Yes Zero Crossing No Zero Pole Purpose Library Description 1 s 1 gt Implement a transfer function specified in terms of poles a
189. el directly e Determine the blocks contained in a model To open the Browser select Show Browser from the File menu The Browser window appears displaying information about the current model This figure shows the Browser window displaying the contents of thec ut ch system Ed clutch Browser BE x File Options Break Apart Detection Break Apart Detect Break Apart Flag Current Friction Model Clutch Pedal Locked Engine Torque system and re Detection Friction Model Blocks in subsystems Requisite Frictior the selected it co nta ins Unlocked Lockup Detection Lockup FSM system Lockup Flag eae T Look Under MJask Dialog I Expand Library Links Contents of the Browser Window The Browser window consists of The systems list The list on the left contains the current system and the subsystems it contains with the current system selected The blocks list The list on the right contains the names of blocks in the selected system Initially this window displays blocks in the top level system The File menu which contains the Print Close Model and Close Browser menu items The M odel Browser e The Options menu which contains these menu items Open System Look Into System Display Alphabetical Hierarchical List Expand All Look Under Mask Dialog and Expand Library Links Options check boxes and buttons Look Under M ask Dialog and Expand L ibrary Links check boxes and Open System and Look Into
190. elect a block with a drop shadow the menu item changes to Hide Drop Shadow The figure below shows a Subsystem block with a drop shadow Libraries Libraries This feature enables users to copy blocks into their models from external libraries and automatically update the copied blocks when the source blocks change Using libraries allows users who develop their own block libraries or who use those provided by others such as blocksets to ensure that their models automatically include the most recent versions of these blocks Terminology It is important to understand the terminology used with this feature Library A collection of library blocks A library must be explicitly created using New Library from the File menu Library block A block in a library Reference block A copy of a library block Link The connection between the reference block and its library block that allows Simulink to update the reference block when the library block changes Copy The operation that creates a reference block from either a library block or another reference block This figure illustrates this terminology a link gt library P7 reference block block Library Source Model or Library Destination Creating a Library To create a library select Library from the New submenu of the File menu Simulink displays a new window labeled Library untitled If an untitled window
191. em Generate the sum of inputs Implement a linear transfer function Implement a transfer function specified in terms of poles and zeros 9 5 9 Block Reference Table 9 5 Nonlinear Library Blocks Block Name Purpose Abs Algebraic Constraint Backlash Combinatorial Logic Coulomb amp Viscous Friction Dead Zone Fen Hit Crossing Logical Operator Look Up Table Look Up Table 2 D Manual Switch Math Function MATLAB Fcn Memory MinMax Multiport Switch Product Quantizer Rate Limiter Relational Operator Relay Output the absolute value of the input Constrain the input signal to zero Model the behavior of a system with play Implement a truth table Model discontinuity at zero with linear gain elsewhere Provide a region of zero output Apply a specified expression to the input Detect crossing point Perform the specified logical operation on the input Perform piecewise linear mapping of the input Perform piecewise linear mapping of two inputs Switch between two inputs Perform a mathematical function Apply a MATLAB function or expression to the input Output the block input from the previous time step Output the minimum or maximum input value Choose between block inputs Generate the product or quotient of block inputs Discretize input at a specified interval Limit the rate of change of a signal Perform the specified relational operation on the input Switch output bet
192. em Current system All systems and above and be el ar T Include Print Log oO r Cancel 3 39 3 Creating a M odel 3 40 When you select either the Current system and below or All systems option two check boxes become enabled In this figure All systems is selected Options Cc C Cc ce Current system Current system Current system All systems F and above and below fo tL T Include Print Log I Look Under Mask Dialog I Expand Unique Library Links cn Selecting the Look Under Mask Dialog check box prints the contents of masked subsystems when encountered at or below the level of the current block When printing all systems the top level system is considered the current block so Simulink looks under any masked blocks encountered Selecting the Expand Unique Library Links check box prints the contents of library blocks when those blocks are systems Only one copy is printed regardless of how many copies of the block are contained in the model For more information about libraries see Libraries on page 3 13 The print log lists the blocks and systems printed To print the print log select the Include Print Log check box Print Command The format of the pri nt command is print ssys device filename sys isthenameof thesystem to be printed The system name must be preceded by thes switch identifier and is the only required argument s ys must be open or must have been open during the current s
193. em is a subsystem whose execution depends on the value of an input signal The signal that controls whether a subsystem executes is called the control signal The signal enters the Subsystem block at the control input Conditionally executed subsystems can be very useful when building complex models that contain components whose execution depends on other components Simulink supports three types of conditionally executed subsystems An enabled subsystem executes while the control signal is positive It starts execution at the time step where the control signal crosses zero from the negative to the positive direction and continues execution while the control signal remains positive Enabled subsystems are described in more detail on page 7 3 A triggered subsystem executes once each time a trigger event occurs A trigger event can occur on therising or falling edge of a trigger signal which can be continuous or discrete Triggered subsystems are described in more detail on page 7 8 A triggered and enabled subsystem executes once on the time step when a trigger event occurs if the enable control signal has a positive value at that step Triggered and enabled subsystems are described in more detail on page 7 11 Enabled Subsystems Enabled Subsystems Enabled subsystems are subsystems that execute at each simulation step where the control signal has a positive value An enabled subsystem has a single control input which can
194. ent data from each Outport block is written to a different variable For example if the system has two Outport blocks to save data from Outport block 1tos peed and the data from Outport block 2 todi st you could specify this command t x speed dist sim e To provide a means for the i nmod andtrim analysis functions to obtain output from the system For more information about using Outports with analysis commands see Chapter 5 r Outport Provides an output port for a sybsystem or model when a subsystem is disabled the output is either held at its last value or set to the Initial output The port number of the Outport block Parameters For conditionally executed subsystems what happens to the block output when the system is disabled Port number Output when disabled held x Initial output FR For conditionally executed subsystems the block output before the subsystem executes and while Apply Revert Help it is disabled Sample Time Inherited from driving block Vectorized Yes 9 105 Product Purpose Generate the product or quotient of block inputs Library Nonlinear Description The Product block multiplies or divides block inputs depending on the value of the Number of inputs parameter x l If the value is a combination of and symbols the number of block inputs is equal to the number of symbols The block icon shows the appropriate symbol adjacent to each in
195. ents 3 20 manipulating with mouse and keyboard 3 25 signals carried on 4 2 widths displaying 3 21 link breaking 3 15 link to library block 3 14 link definition 3 13 link unresolved 3 14 LinkStatus parameter 3 15 i nmod function 5 4 5 9 9 80 Transport Delay block 9 153 i nmod2 function 5 11 Literal Assignment type 6 10 LMI Control Toolbox 1 7 load initial check box 4 15 LoadFcn block callback parameter 3 31 loading from base workspace 4 14 loading initial states 4 15 local Goto tag visibility 9 64 9 71 location of block names 3 9 3 10 logic circuits modeling 9 20 Logical Operator block 9 85 1 9 Index Look Into System menu item 3 43 Look Under Mask Dialog menu item 3 43 Look Under Mask menu item 6 9 Look Up Table 2 D block 9 89 Look Up Table block 9 87 loops algebraic 10 7 orenzs demo 9 163 M macros for SimStruct C 2 Manual Switch block 9 92 manual organization 1 3 Mask Editor 6 9 mask help text 6 6 Mask Subsystem menu item 6 4 6 9 mask type 6 6 6 24 mask workspace 6 5 6 14 masked blocks block descriptions 6 6 control types 6 12 creating icons 6 6 6 17 description 6 24 documentation 6 24 help text 6 25 initialization commands 6 14 looking under 6 9 parameter default values 6 14 parameter prompts 6 10 parameters 6 3 A 23 question marks in icon 6 19 6 20 type 6 24 unmasking 6 9 Math Function block 9 93 mathematical functions performing 9 93 9 119 9 157 MATLAB Fcn block 9 94 simu
196. ep Transfer Fen To Workspace Clock To Workspace The variables y andt appear in the workspace when the simulation is complete The time vector is stored by feeding a Clock block intoa To Workspace block The time vector can also be acquired by entering a variable name for the time on the Workspace I O page of the Simulation Parameters dialog box for menu driven simulations or by returning it using thesi m command see Chapter 4 for more information The To Workspace block can accept a vector input with each input element s trajectory stored as a column vector in the resulting workspace variable 5 3 5 Analyzing Simulation Results Linearization Simulink provides the i nmod anddlinmod functions to extract linear models in the form of the state space matrices A B C and D State space matrices describe the linear input output relationship as x Ax Bu y Cx Du where x u and y are state input and output vectors respectively For example the following model is called mod Feedback Toextract the linear model of this Simulink system enter this command A B C D linmod mod A 2 1 1 1 0 1 1 B 1 0 0 C 0 1 0 0 D 0 1 Inputs and outputs must be defined using Inport and Outport blocks from the Connections library Source and sink blocks do not act as inputs and outputs Inport blocks can be used in conjunction with source blocks using a Sum block linearizati
197. epts one input and generates one output The value of the input signal before the start of the simulation is assumed to be zero The initial output for the block is zero The accuracy of the results depends on the size of the time steps taken in the simulation Smaller steps allow a smoother and more accurate output curve from this block Unlike blocks that have continuous states the solver does not take smaller steps when the input changes rapidly When the input is a discrete signal the continuous derivative of the input is an impulse when the value of the input changes otherwise it is 0 You can obtain the discrete derivative of a discrete signal using 1 y k ay u k u k 1 Taking the z transform Y Z _ 1 2 z 1 uz At At zZ Using inmod tolinearize a model that contains a Derivative block can be troublesome For information about how to avoid the problem see Linearization on page 5 4 Derivative r Derivative Numerical derivative du dt Apply Help Derivative Characteristics Direct Feedthrough Sample Time Scalar Expansion States Vectorized Zero Crossing Yes Continuous N A 0 Yes No 9 35 Digital Clock Purpose Output simulation time at the specified sampling interval Library Sources Description The Digital Clock block outputs the simulation time only at the specified sampling interval At other times the output is held at the previous value 12 34 b
198. er block characteristics Togive Simulink this information call thesi msi zes function at the beginning of mdl nitializeSizes sizes simsizes This function returns an unpopulated si zes structure The table below lists thesi zes structure fields and describes the information contained in each field Table 8 2 Fields in the sizes Structure Field Name Description sizes NumContStates Number of continuous states sizes NumDiscStates Number of discrete states sizes NumOut puts Number of outputs sizes Numi nputs Number of inputs sizes DirFeedthrough Flag for direct feedthrough sizes NumSampl eTi mes Number of sample times 8 11 8 S Functions 8 12 After you initializethesi zes structure call si msi zes again sys simsizes sizes This passes the information inthesi zes structuretosys a vector that holds the information for use by Simulink A Simple M File S Function Example The easiest way to understand how S functions work is to look at a simple example This block takes an input scalar signal and doubles it PeH Sine Wave S Function Scope The M file code that contains the S function is modeled on an S function template called sf unt mp m which is included with Simulink By using the template you can create an M file S function that is very close in appearance toa C MEX file S function This is useful because it makes a transition from an M fileto an C MEX file much easie
199. erates its output by multiplying its vector input by a specified matrix where K is the gain and u is the input If the specified matrix has m rows and n columns then the input to this block should be a vector of length n The output is a vector of length m The block icon always displays K If the matrix contains zeros Simulink converts the matrix gain to a sparse matrix for efficient multiplication Parameters Matrix Gain Matrix Gain mask a nd Dia log Matrix Gain Box Parameters Gain matrix The gain specified as a matrix The default is eye 3 3 eyel3 3 Apply Revert Help Characteristics Direct Feedthrough Yes Sample Time Continuous Scalar Expansion No States 0 Vectorized Yes Zero Crossing No 9 96 Memory Purpose Library Description Parameters and Dialog Box Characteristics Output the block input from the previous integration step Nonlinear The Memory block outputs its input from the previous time step applying a one integration step sample and hold to its input signal This sample model which to provide more useful information would be part of a larger model demonstrates how to display the step size used in a simulation The Sum block subtracts the time at the previous step generated by the Memory block from the current time generated by the clock NOTE Avoid using the Memory block when integrating with ode15s or ode113 unless the input
200. es 0 00 cece eee eee 6 20 The Documentation Page z nnnunnnonnnunnnnnnn 6 24 The Mask Type Field 0 0 c seen rennen nn 6 24 The Block Description Field 000 e eee eee 6 24 The Mask Help Text Field 0 00 eee eee eee 6 25 Conditionally Executed Subsystems 7 Introduction 1 1 2 0 c ee eee 7 2 Enabled Subsystems 0ccce seen eee nun nun nn nn nn nn 7 3 Creating an Enabled Subsystem 0 0 0c eee eee 7 3 Blocks an Enabled Subsystem Can Contain 7 5 Triggered Subsystems cece e cece eee eee 7 8 Creating a Triggered Subsystem 1 1 cee eee 7 9 Function Call Subsystems 2 00 e eee eee 7 10 Blocks a Triggered Subsystem Can Contain 7 10 Triggered and Enabled Subsystems 000000ees 7 11 Creating a Triggered and Enabled Subsystem 7 11 A Sample Triggered and Enabled Subsystem 7 12 S Functions Introduction ueuununnnnnnnnn nn nn nun 82 What Is an S Fungion 2 0 ccc ernennen 82 When ToUseanS Fundion 0 00 c eee eee eee 84 How S Functions Work 0 cece ernennen 8 4 S F unction Concepts 0 cee eee eee 8 8 SampleS Functions 000 c eee en 8 10 Writing S Functions as M Files 000eeeeeeeeeenee 8 11 Defining S Function Block Characteristics 8 11 A Simple M File S Function Example 05 8 12 Examples of M FileS Fun
201. ession If the system name contains spaces or takes more than one line you need to specify the name as a string See the examples below device specifies a device type For a list and description of device types see Using MATLAB Graphics Printing a Block Diagram filename is the PostScript file to which the output is saved Iff i ename exists it is replaced If fi ename does not include an extension an appropriate one is appended For example this command prints a system named untitled print suntitled This command prints the contents of a subsystem named Subl in the current system print sSubl This command prints the contents of a subsystem named Requisite F riction print sRequisite Friction The next example prints a system named Friction Model a subsystem whose name appears on two lines The first command assigns the newline character to a variable the second prints the system cr sprintf n print sFriction cr Model You cannot control the size of the system when print output is sent directly to the printer If the diagram is larger than the page size Simulink reduces it to fit the page To control the size of the print output direct output to an EPS file or toa bitmap then manipulate its size using a word processing program 3 41 3 Creating a M odel The Model Browser 3 42 The Model Browser enables you to e Navigate a model hierarchically e Open systems in a mod
202. et of blocks you can create discrete time dynamic systems that utilize fixed point arithmetic As a result Simulink can simulate effects commonly encountered in fixed point systems for applications such as control systems and time domain filtering Simulink is required The Fixed Point Blockset allows you to simulate fixed point effects in a convenient and productive environment The new blocks provided by the Fixed Point Blockset include blocks for e Addition and subtraction e Multiplication and division e Summation e Gains and constants e Conversion between floating point and fixed point signals e 1 and 2 D lookup tables Blocksets e Logical operators e Relational operators e Conversion saturation of fixed point signals e Switch between two values e Delay e Delta inverse operator e Monitoring signals Signal conversion blocks let you convert between floating point and fixed point signals Using the conversion blocks you can create Simulink block diagrams which consist of both standard Simulink block library components and fixed point blocks For example you can create plant models using the standard Simulink blocks and model the controller with fixed point blocks Data range blocks provide maximum and minimum values encountered during simulation from any point in the block diagram The Fixed Point Blockset lets you build models using unsigned or 2 s complement 8 16 or 32 bit word lengths A combination of bl
203. ete a prompt from the list 1 Select the prompt you want to delete 2 Click on the Delete button to the left of the prompt list 6 11 6 Using M asks to Customize Blocks Moving a Prompt To move a prompt in the list 1 Select the prompt you want to move 2 Tomovethe prompt up one position in the prompt list click on the Up button to the left of the prompt list To move the prompt down one position click on the Down button Control Types Simulink enables you to choose how parameter values are entered or selected You can create three styles of controls edit fields check boxes and popups For example this figure shows the parameter area of a mask dialog box which uses all three styles of controls and the popup is open Parameters Edit control Frequency I Show label Check box control Color red IR x Popup control blue green ellow Defining an Edit Control An edit fidd enables the user to enter a parameter value by typing it intoa field This figure shows how the prompt for the sample edit control was defined Prompt Frequency Controltype Edit z Variable freq Assignment Evaluate zl The value of the variable associated with the parameter f req is determined by the Assignment type defined for the prompt Assignment Value Evaluate The result of evaluating the expression entered in the field Literal The actual string entered in the field 6 12 The Initializ
204. etic operators Relational operators gt lt gt lt The expression returns 1 if the relation is TRUE otherwise it returns 0 Logical operators amp amp The expression returns 1 if the relation is TRUE otherwise it returns 0 Parentheses Mathematical functions abs acos asin atan atan2 ceil cos cosh exp fabs floor hypot In log log10 pow power rem sign sin sinh sqrt tan andtanh Workspace variables Variable names that are not recognized in the list of items above are passed to MATLAB for evaluation Matrix or vector elements must be specifically referenced e g A 1 1 instead of A for the first element in the matrix The rules of precedence obey the C language standards on OU PF WN mB unary pow exponentiation 9 61 Fcn 9 62 Parameters and Dialog Box Characteristics 9 amp amp 10 The expression differs from a MATLAB expression in that the expression cannot perform matrix computations Also this block does not support the colon operator Block input can bea scalar or vector The output is always a scalar For vector output consider using the Math Function block If a block is a vector and the function operates on input elements individually for example thesi n function the block operates on only the first vector element Fen General expression block Use u as the input variable name Example sin u 1 exp 2 3
205. etween two characters to position the insertion point then insert text Toreplace characters drag the mouse to select a range of text to replace then enter the new text To delete an annotation hold down the Shift key while you select the annotation then press the Delete or Backspace key To change the font of all or part of an annotation select the text in the annotation you want to change then choose Font from the Format menu Select a font and size from the dialog box Summary of M ouse and Keyboard Actions Summary of Mouse and Keyboard Actions These tables summarize the use of the mouse and keyboard to manipulate blocks lines and signal labels LMB means press the left mouse button CMB the center mouse button and RMB the right mouse button The first table lists mouse and keyboard actions that apply to blocks Table 0 1 Mouse and Keyboard Actions that Manipulate Blocks Task Microsoft Windows Macintosh X Windows Select one block LMB M ouse button LMB Select multiple Shift LMB Shift mouse button Shift LMB or CMB blocks alone Copy block from Drag block Drag block Drag block another window Move block Drag block Drag block Drag block Duplicate block Connect blocks Disconnect block Ctrl LMB and drag or RMB and drag LMB Shift drag block Option drag block Mouse button Shift drag block Ctrl LMB and drag or RMB and drag LMB Shift drag block or CMB and drag T
206. f the time delay is smaller than the step size the block extrapolates an output point This may result in less accurate results The block cannot use the current input to calculate its output value because the block does not have direct feedthrough at this port Toillustratethis point consider a fixed step simulation with a step size of 1 and the current time at t 5 If the delay is 0 5 the block needs to generate a point at t 4 5 Because the most recent stored time valueis at t 4 the block performs forward extrapolation The Variable Transport Delay block does not interpolate discrete signals Instead it returns the discrete value at t tdday Variable Transport Delay Pa ra meters Variable Transport Delay H r Variable Transport Delay and Dialo g Applies a delay to the first input signal The second input Box specifies the delay time Best accuracy is achieved when the delay is larger than the simulation step size The maximum value of the time del ay i nput The value cannot be negative The default is 10 Parameters Maimun delay The output generated by the block until the simulation time first exceeds the time delay ial hout input The default is 0 Buffer size ary n The number of points the block can store The default is 1024 Apply Revert Help Characteristics Direct Feedthrough Yes of the time delay second input Sample Time Continuous Scalar Expansion Of input and all para
207. fer size 1024 The initial memory allocation for the number of points to store Apply Revert Help Characteristics Direct Feedthrough No Sample Time Continuous Scalar Expansion Of input and all parameters except Initial buffer size Vectori zed Yes Zero Crossing No 9 154 Trigger Purpose Library Description Add a trigger port to a subsystem Connections Adding a Trigger block to a subsystem makes it a triggered subsystem A triggered subsystem executes once on each integration step when the value of the signal that passes through the trigger port changes in a specifiable way described below A subsystem can contain no more than one Trigger block For more information about triggered subsystems see Chapter 7 The Trigger type parameter allows you to choose the type of event that triggers execution of the subsystem rising triggers execution of the subsystem when the control signal rises from zero to a positive value falling triggers execution of the subsystem when thecontrol signal falls from zero to a negative value either triggers execution of the subsystem when the control signal either rises from zero to a positive value or falls from zero to a negative value function call causes execution of the subsystem to be controlled by logic internal to an S function for more information see F unction Call Subsystems in Chapter 7 You can output thetrigger signal by selecting the Show output p
208. fier in the form bl ock port Most block ports are identified by numbering the ports from top to bottom or from left to right such as Gai n 1 or Sum 2 Enable Trigger and State ports are identified by name such as subsystem name Enable subsystem name Trigger or Integrator State delete _line sys x y deletes one of the lines in the system that contains the specified point x y if any such line exists This command removes the line from the my mode system connecting the Sum block to the second input of the Mux block delete _line mymodel Sum 1 Mux 2 add line 11 11 find_system Purpose Syntax Description 11 12 Find Simulink objects with specified parameter values find _system parameterl valuel parameter2 value2 find system SearchDepth depth parameterl valuel find _system obj find_system names find system LookUnderMasks on find system Followlinks on find system parameterl valuel parameter2 value2 searches all open systems and returns a cell array containing the full path names in hierarchical order of all systems subsystems and blocks whose specified parameters have the specified values Searches do not extend into masked systems or library blocks but see the last two forms of the command Case is ignored for parameter names Value strings are case sensitive Any parameters that correspond
209. find an equilibrium point nearx 1 1 u 1 1 enter x0 1 1 u0 1 1 x u y dx options trim sys x0 u0 X 1 0e 11 x 0 1167 0 1167 0 3333 0 0000 1 0000 0 3333 1 0e 11 x 0 4214 0 0003 The number of iterations taken is options 10 ans 25 Example 3 Tofind an equilibrium point with the outputs fixed to1 use y 1 1 iy 1 2 x u y dx trim sys y iy X 0 0009 0 3075 0 5383 0 0004 m 0000 0000 m 5 15 Trim Analysis dx 1 0e 16 0 0173 0 2396 Example 4 Tofind an equilibrium point with the outputs fixed to 1 and the derivatives set to 0 and 1 use y 1 1 iy 12 dx 0 1 idx 1 2 x u y dx options trim sys y 0 1y dx Idx X 0 9752 0 0827 us 0 3884 0 0124 y 1 0000 1 0000 dx 0 0000 1 0000 The number of iterations taken is options 10 ans 13 Limitations When a steady state solution is found better values for x u andy may exist because there is no guarantee of global solutions unless the optimization problem is univariate i e has a single minimum Thus it is important to try a number of starting guesses for x u andy if you seek global solutions t ri m does not work well when the system has discontinuities Algorithm tri m uses a constrained optimization routine which restricts the state derivatives to zero and solves a minimax problem formed from the desired
210. for Masked Block Parameters To change default parameter values in a masked library block follow these steps 1 Unlock the library 2 Open the block to access its dialog box fill in the desired default values and close the dialog box 3 Save the library When the block is copied into a model and opened the default values appear on the block s dialog box For more information about libraries see Chapter 3 Initialization Commands Initialization commands define variables that reside in the mask workspace These variables can be used by all initialization commands defined for the mask by blocks in the masked subsystem and by commands that draw the block icon drawing commands Simulink executes the initialization commands when e The model is loaded e Thesimulation is started or the block diagram is updated e The masked block is rotated e The block s icon needs to be redrawn and the plot commands depend on variables defined in the initialization commands Initialization commands are valid MATLAB expressions consisting of MATLAB functions operators and variables defined in the mask workspace Initialization commands cannot access base workspace variables Terminate initialization commands with a semi colon to avoid echoing results to the command window The Mask Workspace Simulink creates a local workspace called a mask workspace when e The mask contains initialization commands or e The mask defines pro
211. from the Command Line 4 21 Usingthesim Command 0 cece eee eens 4 21 Using theset_param Command 00 00e eee 4 21 Analyzing Simulation Results 5 Viewing Output Trajectories sssssssssnssessnssan 5 2 Using the Scope Block 0 0 cece 5 2 Using Return Variables 0 0 0 c cee en 5 2 Using the To Workspace Block 0 00 e eee ees 5 3 iv _ Contents Linearization sie iis 4 0 ek ee ee eee ee 5 4 Equilibrium Point Determination trim 0000005 5 7 Using Masks to Customize Blocks 6 Introduction 1 ccc eee eee 62 A Sample Masked Subsystem snunnnonnnonnnnnnnn 63 Creating Mask Dialog Box Prompts 00 0005 64 Creating the Block Description and Help Text 6 6 Creating the Block Icon 1 seen seen een nn 66 SUMMARY erpen sn an akg Ra an BE et A In AD Hee 68 The Mask Editor An Overview 000eceneeeeeeuee 69 The Initialization Page 00ccceee eee e eee ee 6 10 Prompts and Associated Variables 00c cee eee 6 10 Control Types 2 02 eee 6 12 Default Values for Masked Block Parameters 6 14 Initialization Commands 2 22 22 cee eee 6 14 The Icon Page ccce cece eee eee 6 17 Displaying Text on the Block ICON eee ee 6 17 Displaying Graphics on the Block Icon 20000 6 18 Displaying a Transfer Function on the Block Icon 6 19 Controlling Icon Properti
212. fter a block s name and or path changes When a Subsystem block s path is changed it recursively calls this function for all blocks it contains after calling its own NameChangeFcn routine When the block is opened This parameter is generally used with Subsystem blocks The routine is executed when you double click on the block or when anopen_system command is called with the block as an argument The OpenFcn parameter overrides the normal behavior associated with opening a block which is to display the block s dialog box or to open the subsystem Before closing a subsystem containing the block or when the block is made part of a new subsystem using the Create Subsystem command Before the block diagram is saved This callback is recursive for Subsystem blocks After the block diagram is saved This callback is recursive for Subsystem blocks 3 31 3 Creating a M odel Table 3 2 Block Callback Parameters Continued Parameter When Executed StartFen After the block diagram is compiled and before the simulation starts StopFen At any termination of the simulation UndoDelete When a block delete is undone 3 32 Tips for Building Models Tips for Building Models Here are some model building hints you might find useful Memory issues In general the more memory the better Simulink performs Using hierarchy More complex models often benefit from adding the hierarchy of subsystems to the model Group
213. function ThessSet Of fsetTime macro which uses this calling syntax assigns the value ssSetOffsetTime S st_index offset time 8 45 8 S Functions wheres istheSi mStruct st_index is the index of the sample time to which the offset applies andoffset_time is the value associated with the specified offset Multirate S Function Blocks Ina multirate S F unction block encapsulate the code that defines each behavior in the md Output and md Update functions with a statement that determines whether a sample hit has occurred at the current time value The ssl sSampl eHi t macro determines whether the current time is a sample hit for a specified sample time The macro has this syntax sslsSampleHit S st_index tid wheres istheSi mStruct st_index identifies a specific sample timeindex and tid isthetask ID tid is an argument tothe md Out put mdi Update and md Derivatives functions For example these statements specify three sample times one for continuous behavior and two for discrete behavior ssSetSampleTime S 0 CONTINUOUS SAMPLE_TI ME ssSetSampleTime S 1 0 75 ssSetSampleTime S 2 1 0 Inthemd Updat e function the following statement would encapsulate the code that defines the behavior for the sample time of 0 75 seconds if sslsSamplehit S 1 tid The second argument 1 corresponds to the second sample time 0 75 seconds Example Defining a Sample Time for a Continuous Block This examp
214. functions provide a powerful mechanism for augmenting and extending Simulink s capabilities Theintroductory sections of this chapter describe what an S function is and when and why you might use one This chapter then presents a comprehensive description of how to write your own S functions What Is an S Function An S function is a programmatic description of a dynamic system S functions can be written using MATLAB or C C language S functions are compiled as ME X files using the mex utility described in the Application Program Interface Guide As with other ME X files they are dynamically linked into MATLAB when needed S functions use a special calling syntax that enables you to interact with the ODE solvers This interaction is very similar totheinteraction that takes place between the solvers and built in Simulink blocks The form of an S function is very general and can accommodate continuous discrete and hybrid systems As a result nearly all Simulink models can be described as S functions S functions are incorporated into Simulink models by using the S F unction block in the Nonlinear Library Use the S F unction block s dialog box to specify the name of the underlying S function as illustrated in the figure below Introduction A model that includes two S Function blocks File Edit Simulation Format mysfun S Function gt mysfun S Function S Function dialog box
215. g all data logging variables being used in the model Other data logging variables are defined on other Scope blocks To Workspace blocks and simulation return variables such as time states and outputs Being able to save Scope data to the workspace means that it is not necessary to send the same data stream to both a Scope block and a To Workspace block The Scope relies on its data history for zooming and auto scaling operations If the number of points is limited to 1 000 and the simulation generates 2 000 points only the last 1 000 are available for regenerating the display Sample Time Inherited from driving block or settable States 0 9 127 Selector Purpose Select input elements Library Connections Description The Selector block generates as output selective elements of the input vector The Elements parameter defines the order of the input vector elements in the oe h output vector The parameter must be specified as a vector unless only one a element is being selected For example this model shows the Selector block icon and the output for an input vector of 2 4 6 8 10 andan Elements parameter valueof 5 1 3 Constant Selector Display The block icon displays the ordering of input vector elements graphically If the block is not large enough it displays the block name Parameters Selector and Dialo eevee g Selects or re orders the specified elements of the input Box vector y u Ele
216. gcb Gain ans 1 Iv le gcbh gcs gcbh Purpose Syntax Description Examples See Also Get the handle of the current Simulink block gcbh gcbh returns the handle of the current block in the current system You can use this command to identify or address blocks that have no parent system The command should be most useful to blockset authors This command returns the handle of the most recently selected block gt gt ans gcb gcbh 281 0001 11 15 gcs Purpose Syntax Description Examples See Also 11 16 Get the full path name of the current Simulink system gcs gcs returns the full path name of the current system The current system is During editing the current system is the system or subsystem most recently clicked in During simulation of a system that contains S F unction blocks the current system is the system or subsystem containing the S Function block that is currently being evaluated During callbacks the current system is the system containing any block whose callback routine is being executed During evaluation oftheMaskInitiali zation string the current system is the system containing the block whose mask is being evaluated This example returns the path of the system that contains the most recently selected block gt gt gcs ans clutch Locked gcb get param Purpose Syntax Description Examples See Also Get Simulink
217. gle one Instead of requiring the user of the model to open each block and enter parameter values those parameter values can be entered on the mask dialog box and passed to the blocks in the masked subsystem Provide a more descriptive and helpful user interface by defining a dialog box with your own block description parameter field labels and help text Define commands that compute variables whose values depend on block parameters Create a block icon that depicts the subsystem s purpose Prevent unintended modification of subsystems by hiding their contents behind a customized interface A Sample M asked Subsystem A Sample Masked Subsystem This simple subsystem models the equation for aline y mx b A samplemask ioj x _ Eile Edit Simulation Format En Intercept Ordinarily when you double click on a Subsystem block the Subsystem block opens displaying its blocks in a separate window Themx b subsystem contains a Gain block named Slope whose Gain parameter is specified as m and a Constant block named Intercept whose Constant value parameter is specified as b These parameters represent the slope and intercept of a line In this example a custom dialog box and icon are created for the subsystem One dialog box contains prompts for both the slope and the intercept After creating the mask double clicking on the Subsystem block opens the mask dialog box The mask dialog box an
218. gt The Sum block draws plus and minus signs beside the appropriate ports and redraws its ports to match the number of signs specified in the List of signs parameter If the number of signs is changed ports are added or deleted from the bottom of theicon If necessary Simulink resizes the block to show all input ports 9 142 Sum Parameters and Dialog Box Characteristics r Sum Add or subtract inputs Specify one of the following a or for each input port e g b scalar greater than 1 sums all input ports c 1 sums all elements of single input vector Parameters List of signs Apply Revert Help Direct Feedthrough Yes A constant or a combination of and symbols Specifying a constant causes Simulink to redraw the block with that number of ports all with positive polarity A combination of plus and minus signs specifies the polarity of each port where the number of ports equals the number of symbols used Sample Time Inherited from driving blocks Scalar Expansion Yes States 0 Vectorized Yes Zero Crossing No 9 143 Sw itch Purpose Library Description EJ Parameters and Dialog Box Characteristics 9 144 Switch between two inputs Nonlinear The Switch block propagates one of two inputs to its output depending on the value of a third input called the control input If the signal on the control second input is greater than or equ
219. h the Enable and Trigger blocks from the Connections library into an existing subsystem Simulink adds enable and trigger symbols and enable and trigger and enable control inputs to the Subsystem block icon Subsystem 7 11 7 Conditionally Executed Subsystems 7 12 You can set output values when a triggered and enabled subsystem is disabled as you would for an enabled subsystem For more information see Setting Output Values while the Subsystem Is Disabled on page 7 4 Also you can specify what the values of the states are when the subsystem is re enabled See Setting States When the Subsystem Becomes Re enabled on page 7 4 Set the parameters for the Enable and Trigger blocks separately The procedures are the same as those described for the individual blocks A Sample Triggered and Enabled Subsystem A simple example of a triggered and enabled subsystem is illustrated in the model below Trigger Signal Sine Wave Display Subsystem u Enable Trigger Unit Delay S F unctions Introduction Introduction Writing S Functions as M Files Writing S Functions as C MEX Files mdIDerivatives mdi nitializeConditions mdll nitializeSampleTimes mdllnitializeSizes mdlOutputs mdiITerminate mdlU pdate 8 2 8 11 8 27 8 55 8 56 8 58 8 60 8 61 8 63 8 64 8 S Functions 8 2 Introduction S functions System
220. hange the step size The additional output is produced using a continuous extension formula at those points The Simulation Parameters Dialog Box Produce Specified Output Only The Produce specified output only choice provides simulation output only at the specified output times Specifying this parameter does not affect the step sizes used by the solver This choice is useful when comparing different simulations to ensure that the simulations produce output at the same times Comparing Output Options A sample simulation generates output at these times 0 2 5 5 8 5 10 Choosing Refine Output and specifying a refine factor of 2 generates output at these times 0 1 254 Qebe Bo Pye By Be 9o25 10 Choosing the Produce Additional Output option and specifying 0 10 generates output at these times 0 4 2 265 Be 8 By by Fin Be BS we 10 Choosing the Produce Specified Output Only option and specifying 0 10 generates output at these times 4 13 4 Running a Simulation 4 14 The Workspace I O Page You can direct simulation output to workspace variables and get input and initial states from the workspace On the Simulation Parameters dialog box select the Workspace I O tab This page appears EJ Simulation parameters untitled BEI Salver Workspace 1 0 Diagnostics Load from workspace Save to workspace T Input IV Time tout I States row IV Output u States I Load initial anti I Save final Fi
221. hat avoid the problems These blocks are in the Simulink Extras library in the Linearization sublibrary You access the E xtras library by opening the Blocksets amp Toolboxes icon e For the Derivative block use the Switched derivative for linearization e For the Transport Delay block use the Switched transport delay for linear ization Using this block requires that you have the Control System Tool box 5 5 5 Analyzing Simulation Results When using a Derivative block you can also try to incorporate the derivative termin other blocks For example if you havea Derivative block in series with a Transfer F cn block it is better implemented although this is not always possible with a single Transfer Fcn block of the form S s a Inthis example theblocks on theleft ofthisfigurecan bereplaced by the block on the right du dt Equilibrium Point Determination trim Equilibrium Point Determination trim The Simulink t ri m function determines steady state equilibrium points Consider for example this model called mod Feedback You can usethet ri m function to find the values of theinput and the states that set both outputs to 1 First make initial guesses for the state variables x and input values u then set the desired value for the output y x 0 0 0 u 0 y 1 1 Use index variables to indicate which variables are fixed and which can vary ix Don t fi
222. he From Workspace block described in Chapter 9 For example these statements define a matrix that can be used to provide input values for three Inport blocks t 0 0 1 10 u cos t sin t tan t ut t ul Saving Output to the Workspace You can specify return variables by selecting the Time States and or Output check boxes in the Save to workspace area of this dialog box page Specifying return variables causes Simulink to write values for thetime state and output trajectories as many as are selected into the workspace Toassign values to different variables specify those variable names in the field to the right of the check boxes To write output to more than one variable specify the variable names in a comma separated list The Save options area enables you to restrict the amount of output saved To set a limit on the number of rows of data saved select the check box labeled Limit rows to last and specify the number of rows to save To apply a decimation factor enter a value in the field to the right of the Decimation label For example a value of 2 saves every other point generated Loading and Saving States Initial conditions which are applied to the system at the start of the simulation are generally set in the blocks You can override initial conditions set in the blocks by specifying them in the States area of this page You can also save the final states for a simulation and apply them to another simula
223. he Icon page EJ Mask Editor untitled Subsystem Bel x Icon Initialization Documentation Mask type The mask type Drawing commands Commands that draw the block icon Icon frame Visible Parameters that control theicon appearance Icon transparency Opaque Icon rotation Fixed Drawing coordinates Autoscale Apply Revert Unmask Help Close Drawing commands have access to all variables in the mask workspace L Le Le Le i Drawing commands can display text one or more plots or show a transfer function If you enter morethan one command the results of the commands are drawn on the icon in the order the commands appear Displaying Text on the Block Icon To display text on the icon enter one of these drawing commands disp text or disp variabl ename text x y text ortext x y stringvariabl ename fprintf text or fprintf format variabl ename 6 17 6 Using M asks to Customize Blocks 6 18 Thedi sp command displayst ext or the contents of vari abl ename centered on the icon Thetext command places a character string text or the contents of stringvariabl ename at a location specified by the point x y The units depend on the Drawing coordinates parameter For more information see Controlling Icon Properties on page 6 20 Thef printf command displays formatted text centered on the icon and can display t ext along with the contents
224. he block u 1 is added tot andthe macross Set TNext sets the time of next hit equal tot u 1 delaying the output by the amount of time set in u 1 Creating General Purpose S Function Blocks General purpose S F unction blocks can be used in a variety of applications To make the block generic you can specify that certain block characteristics be W riting S Functions as C MEX Files dependent on the number of inputs to the S Function block To do this assign the macro DY NAMI CALLY_ 1 ZED tothe dependent characteristics the value of thesesi zes fields are determined during the compilation of the simulation Thesi zes structure fields that can be set based on the number of inputs include e The number of continuous states e The number of discrete states e The number of outputs e The number of inputs e The number of real work vector elements e The number of integer work vector elements e The number of pointer work vector elements For a discussion of work vectors see Allocating Work Vectors and Setting Their Values on page 8 48 The following statements included in the mdi Initiali zeSi zes function set the number of continuous states the number of outputs and the number of inputs to the number of S F unction block inputs ssSetNumContStates S DYNAMICALLY SIZED ssSetNumOut puts S DYNAMICALLY _SI ZED ssSetNuml nputs S DYNAMICALLY SIZED Note that dynamically sized S functions can determine when t
225. he dashed line Mask r SampleMaskedBlock mask r Gain Models the equation for a line y mx b Wo rkspace Scalar or vector gain y k u The slope and intercept are mask block parameters arameters Gain L L Hem Parameters I m 4 Slope 3 Intercept i Intercept T Constant Apply Revert iz Outputs a constant P t i S b srameters FH L Constant value Apply Revert Help 6 15 6 Using M asks to Customize Blocks 6 16 Debugging Initialization Commands You can debug initialization commands in these ways Specify an initialization command without a terminating semicolon to echo its results to the command window Place akeyboard command in the initialization commands to stop execution and give control to the keyboard F or more information see the help text for thekeyboard command Enter either of these commands in the MATLAB command window dbstop if error dbstop if warning If an error occurs in the initialization commands execution stops and you can examine the mask workspace For more information see the help text for thedbst op command The Icon Page The Icon Page The Icon page enables you to customize the masked block s icon You create a custom icon by specifying commands in the Drawing commands field You can create icons that show descriptive text state equations and graphics This figure shows t
226. he next table lists mouse and keyboard actions that apply to lines Table 0 2 Mouse and Keyboard Actions that Manipulate Lines Task Microsoft Windows Macintosh X Windows Select one line Select multiple lines Draw branch line LMB Shift LMB Ctrl drag line or RMB and drag line Mouse button Shift mouse button Option drag line LMB Shift LMB or CMB alone Ctrl drag line or RMB drag line 3 25 reating a M odel gt c 3 26 Table 0 2 Mouse and Keyboard Actions that Manipulate Lines Continued Task Microsoft Windows Macintosh X Windows Route lines around blocks Move line segment Move vertex Create line segments Shift draw line segments Drag segment Drag vertex Shift drag line Shift draw line Shift draw line segments segments or CMB and draw segments Drag segment Drag segment Drag vertex Drag vertex Shift drag line Shift drag line or CMB drag line The next table lists mouse and keyboard actions that apply to signal labels Table 0 3 Mouse and Keyboard Actions that Manipulate Signal Labels Action Microsoft Windows Macintosh X Windows Create signal label Copy signal label Move signal label Edit signal label Delete signal label Double click on line then type label Ctrl drag label Drag label Click in label then edit Shift click on label then press Delete Double click on li
227. he solvers there is no difference in the solutions To generate output points only at the sample hits choose one ofthediscrete solvers 10 11 10 Additional Topics 10 12 Multirate Systems Multirate systems contain blocks that are sampled at different rates These systems can be modeled with discrete blocks or both discrete and continuous blocks For example consider this simple multirate discrete model Constant DTF2 2 For this examplethe DTF 1 Discrete Transfer F cn block s Sample time is set to 1 0 1 which gives it an offset of 0 1 The DTF 2 Discrete Transfer F cn block s Sample time is set to0 7 with no offset Starting the simulation and plotting the outputs using thest airs function t x y sim multirate 3 stairs t y produces this plot For the DTF 1 block which has an offset of 0 1 thereisnooutput untilt 0 1 Because the initial conditions of the transfer functions are zero the output of DTF 1 y 1 is zero before this time Discrete Time Systems Sample Time Colors Simulink identifies different sample rates in a model using the sample time color feature which shows sample rates by applying the color scheme shown in this table Table 10 2 Sample Time Colors Color Use Black Continuous blocks Magenta Constant blocks Yellow Hybrid subsystems grouping blocks or Mux or Demux blocks grouping signals with varying sample times Red Fastest discre
228. henumber of output points by the specified factor producing smoother output Refi ne applies only tothe variable step solvers It is ignored if output times are specified Rel Tol positive scalar le 3 Reativeerror tolerance This property applies to all elements of the state vector The estimated error in each integration step satisfies e i lt max Rel Tol abs x i AbsTol i This property applies only to the variable step solvers and defaults to 1e 3 which corresponds to accuracy within 0 1 Solver VariableStepDiscrete ode45 ode23 odell3 odel5s ode23s FixedStepDiscrete ode5 ode4 ode3 ode2 odel Method to advancetime This property specifies which solver is used to advance time SrcWorkspace base current parent Where to evaluate expressions This property specifies the workspace in which to evaluate MATLAB expressions defined in the model simset Examples See Also Trace minstep siminfo compile Tracing facilities This property enables simulation tracing facilities specify one or more as a comma separated list e The mi nstep trace flag specifies that simulation will stop when the solution changes so abruptly that the variable step solvers cannot takea step and satisfy the error tolerances By default Simulink issues a warning message and continues the simulation e The si mi nfo trace flag provides a short summary of the simulation parameters in effect at the
229. hey aren t connected usingthessGetI nputConnected S andssGet Out put Connected S macros Specifying Parameter Values Interactively In addition to their inputs outputs and states S functions can also accept parameters These parameters are set interactively using the S F unction parameters field of the block s dialog box If you define parameters interactively you should follow these steps when you create the S function 1 Determine the order in which the parameters are to be specified in the block s dialog box 2 Inthemd nitializeSizes function usethessSet Num nput Args macro to tell Simulink how many parameters are passed in to the S function Specify 8 43 8 S Functions S as the first argument and the number of parameters you are defining interactively as the second argument 3 Access these input arguments in the S function using thes s Get Arg macro Specify S as thefirst argument and the relative position of the parameter in the list entered on the dialog box 0 is the first position as the second argument When you run the simulation specify parameter names or values in the S Function parameters field of the block s dialog box The order of the parameters names or values must be identical to the order that you defined them in step 1 above If you specify variable names they do not need to be the same as the names used in the MEX file For example the following codeis part of a device driver S function Fou
230. hrough F or more information see Algebraic Loops on page 10 7 Sample Time how the block s sample time is determined whether by the block itself as is the case with discrete and continuous blocks or inherited from the block that drives it or is driven by it For more information see Sample Time on page 10 11 Scalar Expansion whether or not scalar values are expanded to vectors Some blocks expand scalar inputs and or parameters as appropriate For more information see Scalar Expansion of Inputs and Parameters on page 3 11 States the number of discrete and continuous states Vectorized whether the block accepts and or generates vector signals For more information see Vector Input and Output on page 3 11 Zero Crossings whether the block detects state events For more information see Zero Crossings on page 10 3 The Simulink Block Libraries The Simulink Block Libraries Simulink organizes its blocks into block libraries according to their behavior The simulink window displays the block library icons and names e The Sources library contains blocks that generate signals e The Sinks library contains blocks that display or write block output e TheDiscretelibrary contains blocks that describe discrete time components e The Linear library contains blocks that describe linear functions e The Nonlinear library contains blocks that describe nonlinear functions e The Con
231. ice that the Stop time is set to 10 0 its default value EJ Simulation parameters untitled x Solver Workspace 1 0 Diagnostics Simulation time Starttime 00 Stoptim 100 Stop time parameter Solver options Type Yariable step M ode45 Dormand Prince zi sO Max step size auto Relative tolerance 1e 3 Initial step size auto Absolute tolerance 1e 6 Output options Refine output x Refine factor 1 Apply Beven Help Close Close the Simulation Parameters dialog box by clicking on the Close button Simulink applies the parameters and closes the dialog box Choose Start from the Simulation menu and watch the traces of the Scope block s input EJ Scope P 212 E Time offset 0 Thesimulation stops when it reaches the stop time specified in the Simulation Parameters dialog box or when you choose Stop from the Simulation menu Building a Simple M odel Tosave this model choose Save from the File menu and enter a filename and location That file contains the description of the model Toterminate Simulink and MATLAB choose Exit MATLAB on a Microsoft Windows system Quit MATLAB on an X Windows system or Quit on a Macintosh from the File menu You can alsotypequit in the MATLAB command window If you want to leave Simulink but not terminate MATLAB just close all Simulink windows This exercise showed you how to perform some commonly used model building tasks The
232. ilding Models 00 cceeeeeee eee eens 3 33 Modeling Equations 000ceceeee eee e eee eee 3 34 Converting Celsius to Fahrenheit 0005 3 34 Modeling a Simple Continuous System 00 00s 3 35 Saving a Model ccese eee eee eee eae 3 38 Printing a Block Diagram 00 cceee eee eens 3 39 Print Dialog BOX rari eee 3 39 Print Command 0000 een een nennen 3 40 The Model Browser 0 c0eceeeeeeeee nun eee eae 3 42 Contents of the Browser Window 2 222 rennen 3 42 Interpreting List Contents 000 e eee eee 3 43 Ending a Simulink Session z snunnnonnnunnnnnnn 3 45 A Introduction zurununnnnnn nun nun nn nn nn nn 4 2 Using Menu Commands 0 rennen tees 4 2 Running a Simulation from the Command Line 4 3 Running a Simulation Using Menu Commands 4 4 Setting Simulation Parameters and Choosing the Solver 4 4 Applying the Simulation Parameters 00 eee 4 4 Starting the Simulation 0 000 a 4 4 The Simulation Parameters Dialog Box 0000008 4 6 The Solver Page 0 cece eee 4 6 The Workspace l O Page 0 20 c eee eee eee 4 14 The Diagnostics Page 1 2 eee eee 4 17 Improving Simulation Performance and Accuracy 4 19 Speeding Up the Simulation saaana cc eee eee 4 19 Improving Simulation Accuracy 200 eee eee eee 4 20 Running a Simulation
233. ime Discrete Scalar Expansion No States Length of Denominator parameter 1 Vectorized No Zero Crossing No Discrete Zero Pole Purpose Library Description 21 220 5 gt Parameters and Dialog Box 9 50 Implement a discrete transfer function specified in terms of poles and zeros Discrete The Discrete Zero Pole block implements a discrete system with the specified zeros poles and gain in terms of the delay operator z A transfer function can be expressed in factored or zero pole gain form which for a single input single output system in MATLAB is Ze _ 2 41 2 22 2 Zm H Keay Kup Na Py eP where Z represents the zeros vector P the poles vector and K the gain The number of poles must be greater than or equal to the number of zeros n gt m If the poles and zeros are complex they must be complex conjugate pairs The block icon displays the transfer function depending on how the parameters are specified See the description of the Zero Pole block on page 9 165 for more information Discrete Zero Pole r Discrete Zero Pole Matrix expression for zeros Vector expression for poles and gain Output width equals the number of columns in zeros matrix or one if zeros is a vector Parameters Zeros 1 Poles 0 0 5 The matrix of zeros The default is 1 The vector of poles Thedefaultis 0 0 5 Gain 1 The gain The default is1 Sample time F
234. ines 3 30 closing 11 6 creating 3 3 11 18 editing 3 3 name getting 11 7 organizing and documenting 3 33 parameters A 3 printing 3 39 saving 2 13 3 38 selecting entire 3 5 simulating 4 22 tips for building 3 33 modifying libraries 3 14 Monte Carlo analysis 4 21 mouse actions summary 3 25 moving annotations 3 24 blocks and lines 3 7 blocks between windows 3 7 blocks in a model 2 9 3 7 line segments 3 19 line vertices 3 21 mask prompts 6 12 signal labels 3 22 Mu Analysis and Synthesis Toolbox 1 7 multiplying block inputs by constant variable or expression 9 70 by matrix 9 96 during simulation 9 136 together 9 106 Multiport Switch block 9 99 multirate S F unction blocks 8 46 multirate systems 10 11 10 12 linearization 5 10 Mux block 9 101 changing number of input ports 2 9 N NAG Foundation Toolbox 1 7 NameChangeFcn block callback parameter 3 31 names blocks 3 9 C MEX file routines 8 7 copied blocks 3 6 model files 3 38 Nan values in mask plotting commands 6 19 Neural Network Toolbox 1 8 N ew Library menu item 3 13 New menu item 3 3 new system command 3 13 11 18 newline in block name 11 3 Nonlinear block library 9 6 block parameters A 16 Nonlinear Control Design Blockset 1 15 nonlinear systems spectral analysis of 9 18 Normalized icon drawing coordinates 6 7 6 22 normally distributed random numbers 9 111 numerical differentiation formula 4 9 numerical integration 10 2 1 11 Index 1 12 0 o
235. ing blocks simplifies the top level of the model and can make it easier to read and understand the model For more information see Creating Subsystems on page 3 27 The Model Browser described on page 3 42 provides useful information about complex models Cleaning up models Well organized and documented models are easier to read and understand Signal labels and model annotations can help describe what is happening in a model For more information see Signal Labels on page 3 22 and Annotations on page 3 24 Modeling strategies If several of your models tend to use the same blocks you might find it easier to save these blocks in a model Then when you build new models just open this model and copy the commonly used blocks from it You can create a block library by placing a collection of blocks into a system and saving the system You can then access the system by typing its namein the MATLAB command window Generally when building a model design it first on paper then build it using the computer Then when you start putting the blocks together intoa model add the blocks to the model window before adding the lines that connect them This way you can reduce how often you need to open block libraries 3 33 3 Creating a M odel Modeling Equations 3 34 One of the most confusing issues for new Simulink users is how to model equations Here are some examples that may improve your understanding of how to
236. ing which points to write If the file exists at the time the simulation starts the block overwrites its contents To File Parameters H r To File a nd Dia log Writes time and input to specified MAT file in row format Box Time is in row 1 Parameters Filename The name of the MAT file that holds the matrix untitled mat TABIRA The name of the matrix contained in the named ans file Decimation 1 A decimation factor The default value is 1 Sample Time 4 The sample time at which to collect points Apply Revert Help Characteristics Sample Time Inherited from driving block Vectorized Yes 9 147 To Workspace Purpose Library Description simout 9 148 Write data to a matrix in the workspace Sinks The To Workspace block writes its input to the specified matrix in the workspace The block writes its input row by row where each row consists of all input vector elements at a time step If the matrix already exists its contents are overwritten The matrix has this form ul u2 un ul u2 un Ulsinal U2tinal UNfinal The amount of data written and the time steps at which the data is written are determined by block parameters e The Maximum number of rows parameter indicates how many data rows to save If thesimulation generates more rows than the specified maximum the simulation saves only the most recently generated rows To capture all the data set this value toi nf
237. ining a system of continuous state equations x Ax Bu y Cx Du Generate a continuous linear system A 0 09 0 01 1 0 B 1 1 0 2 C 0 2 1 Bl D 3 0 1 0 Dispatch the flag switch flag case 0 8 15 8 S Functions 8 16 sys x0 str ts mdlInitializeSizes A B C D Initialization case 1 Sys case 3 Sys md Derivatives t x u A B C D Calculate derivatives mal Outputs t x u A B C D Calculate outputs case 2 4 9 Unused flags Sys otherwise error Unhandled flag num2str flag Error handling end end csfunc Ys s 2 gt gt gt gt gt gt 2 mdlInitializesizes Ret cal urn the sizes initial conditions and sample times for the unction ion sys x0 str ts mdl Il nitializeSizes A B C D simsizes for a sizes structure fill it in and convert it to a sizes array izes 5 5 5 5 si 5 5 5 ys izes izes izes zes izes izes N N N N D N 5 umContStates umDiscStates umOut puts uml nputs umSamp eTi mes imsizes sizes simsizes Feedthrough f Matrix D is nonempty u PrN NY Oo PY initialize the initial conditions x0 zeros 2 1 W riting S Functions as M Files str is an empty matrix str Initialize the array of sample times in this example the sample time is continuo
238. initial guesses The Algebraic Constraint block constrains its input signal F z to zero and outputs an algebraic state z This block outputs the value necessary to produce a zero at the input The output must affect the input through some feedback path You can provide an initial guess of the algebraic state value in the block s dialog box to improve algebraic loop solver efficiency A scalar algebraic loop represents a scalar algebraic equation or constraint of the form F z 0 where z is the output of one of the blocks in the loop and the function F consists of the feedback path through the other blocks in the loop to the input of the block In the simple one block example shown on the previous page F z z u z In the vector loop example shown above the equations are z2 z1 1 0 z2 z1 1 0 Algebraic loops arise when a model includes an algebraic constraint F z 0 This constraint may arise as a consequence of the physical interconnectivity of thesystem you are modeling or it may arise because you are specifically trying to model a differential al gebraic system DAE When a model contains an algebraic loop Simulink calls a loop solving routine at each timestep The loop solver performs iterations to determine the solution to the problem if it can As a result models with algebraic loops run slower than models without them How Simulink W orks To solve F z 0 the Simulink loop solver uses Newton s method with weak
239. input signal minus the lower limit and one to detect when the dead zone is exited the input signal minus the upper limit Hit One to detect when the input crosses the threshold These Crossing zero crossings are not affected by the Disable zero crossing detection check box in the Simulation Parameters dialog box Integrator If the reset port is present to detect when a reset occurs If the output is limited there are three zero crossings one to detect when the upper saturation limit is reached one to detect when the lower saturation limit is reached and one to detect when saturation is left MinMax One for each element of the output vector to detect when an input signal is the new minimum or maximum Relay One if the relay is off to detect the switch on point If the relay is on to detect the switch off point Relational One to detect when the output changes Operator Saturation Two one to detect when the upper limit is reached or left and one to detect when the lower limit is reached or left Sign One to detect when the input crosses through zero Step One to detect the step time Subsystem For conditionally executed subsystems one for the enable port if present and one for the trigger port if present Switch One to detect when the switch condition occurs How Simulink W orks Algebraic Loops Some Simulink blocks have input ports with direct feedthrough This means that the output of these blocks cann
240. irst x input is delayed by an amount of time determined by the second input dt u 2 y t dt u t define S_FUNCTION_NAME vsfunc include simstruc h mdlInitializeSizes initialize the sizes structure static void mdllnitializeSizes SimStruct S ssSetNumContStates S 0 number of continuous states ssSetNumDiscStates S 1 number of discrete states ssSetNuml nputs S 2 number of inputs ssSetNumOut puts S 1 number of outputs ssSetDirectFeedThrough S 1 direct feedthrough flag set because next sample hit x depends on input u ssSetNumSampleTimes S 1 number of sample times ssSetNumSFcnParams S 0 number of input arguments W riting S Functions as C M EX iles ssSetNumRWork S 0 number of real work vector elements ssSetNuml Work S 0 number of integer work vector elem s ssSetNumPWork S 0 number of pointer work vector elem s mdllnitializeSampleTimes initialize sample times array static void mdll nitializeSampleTimes SimStruct S ssSetSampleTime S 0 VARIABLE SAMPLE TI ME ssSetOffsetTime S 0 0 0 mdllnitializeConditions initialize the states static void mdll nitializeConditions double x0 SimStruct S x0 0 0 0 mdi GetTi meOfNextVarHit Get the time of the next x variable sample time hit define MDL_GET_TIME_OF_NEXT_VAR_HIT static void mdi GetTi meOfNex
241. is figure shows the icon drawn using these vectors X 0 2 3 4 9 Y 4 6 3 5 8 e Pixel draws theicon with X and Y values expressed in pixels The icon is not automatically resized when the block is resized To force the icon to resize with the block define the drawing commands in terms of the block size This example demonstrates how to create an improved icon for the mx b sample masked subsystem discussed earlier in this chapter These 6 22 The Icon Page initialization commands define the data that enables the drawing command to produce an accurate icon regardless of the shape of the block pos get_param gcb Position width pos 3 pos 1 height pos 4 pos 2 x 0 width if m gt 0 y 0 m width end if m lt 0 y height height m width end The drawing command that generates this icon ispl ot x y 6 23 6 Using M asks to Customize Blocks 6 24 The Documentation Page The Documentation page enables you to define or modify the type description and help text for a masked block This figure shows how fields on the Documentation page correspond to the mx b sample mask block s dialog box EJ Mask Editor samplemask mx b _ x Icon Initialization Documentation Mask type SampleMaskedBlock SampleMaskedBlock mask Models the equation for a line y mx b The slope and intercept are mask block parameters Block description
242. is possible to pass additional parameters into your M file S function For an example of how to do this seeli mi ntm min thet oo box si mulink blocks directory 8 25 8 S Functions Writing S Functions as C MEX Files A C MEX filethat defines an S F unction block must provide information about the model Simulink needs that information during simulation Asthe simulation proceeds Simulink the ODE solver and the ME X file interact to perform specific tasks These tasks include defining initial conditions and block characteristics and computing derivatives discrete states and outputs C MEX file S functions have the same structure and perform the same functions as M file S functions Simulink includes a template file for writing C MEX file S functions calledsfuntmpl c The MEX file must define specific functions that provide the information needed to perform these tasks as well as contain statements that include other necessary code The table below describes the functions that Simulink calls during the simulation in the order they are called Every S function ME X file must contain all of these functions even if not all of them are used in a model These functions are described in detail later in this section Table 8 3 Functions Called During a Simulation Simulation Stage S Function Routine Initialization of block size information mdl lnitializeSizes sample times and initial conditions mdl nitializeSampl eTi
243. isplays a minus sign beforetheir names To display systems alphabetically select the Display Alphabetical List menu item on the Options menu Ending a Simulink Session Ending a Simulink Session Terminate a Simulink session by closing all Simulink windows Terminate a MATLAB session by choosing one of these commands from the File menu e On a Microsoft Windows system Exit MATLAB e On a Macintosh system Quit e On an X Windows system Quit MATLAB 3 Creating a M odel 3 46 Running a Simulation Introduction Using Menu Commands i Running a Simulation from the Command Line Running a Simulation Using Menu Commands Setting Simulation Parameters and Choosing the Solver Applying the Simulation Parameters Starting the Simulation The Simulation Parameters Dialog Box The Solver Page ae The Workspace I O Page The Diagnostics Page Improving Simulation Performance and Accuracy Speeding Up the Simulation Improving Simulation Accuracy Running a Simulation from the Command Line Using the sim Command Using the set_param Command sim simset simget 42 42 43 44 44 44 44 4 6 46 4 14 4 17 4 19 4 19 4 20 4 21 4 21 4 21 4 22 4 24 4 28 4 Running a Simulation 4 2 Introduction You can run a simulation either by using Simulink menu commands or by entering commands in the MATLAB command window Many users use me
244. itching between values 9 117 trajectories viewing 5 2 trigger signal 7 10 variables 4 26 vector or scalar 3 11 writing to file 4 5 9 146 writing to workspace 4 5 4 15 9 148 zero within range 9 28 Index output ports capping unconnected 9 145 Enable block 7 5 Trigger block 7 10 P parameter undefined error message 6 20 parameters blocks A 7 A 10 A 22 getting values of 11 17 masked blocks A 23 model A 3 setting values of 11 22 S functions 8 25 Parameters menu item 2 12 4 4 4 6 ParentClosefcn block callback parameter 3 31 Partial Differential Equation Toolbox 1 8 Paste menu item 3 6 3 7 path specifying 11 3 Pause menu item 4 5 penddemo demo 8 4 perturbation factor 5 9 perturbation levels 5 11 phase shifted wave 9 132 piecewise linear mapping 9 87 9 89 Pixel icon drawing coordinates 6 22 pl ot command and masked block icon 6 18 plotting input signals 9 121 9 163 pointer work vector example 8 49 popup control type 6 13 port labels 9 103 9 141 ports block orientation 3 8 labeling in subsystem 3 29 Post LoadFcn model callback parameter 3 30 Post SaveFcn block callback parameter 3 31 Post SaveFcn model callback parameter 3 30 PostScript file printing to 3 41 PreLoadFcn model callback parameter 3 30 PreSavefcn block callback parameter 3 31 PreSaveFcn model callback parameter 3 30 Print Browser menu item 3 42 print command 3 39 Print menu item 3 39 printing block diagrams 3 39 to bitmap 3 41 to EPS file
245. itions When an enabled subsystem restarts executes after having been disabled the States when enabling parameter determines what happens to the states of blocks contained in the enabled subsystem e reset resets the states to their initial conditions zero if not defined e held holds the states at their previous values You can output the enabling signal by selecting the Show output port check box Selecting this option allows the system to process the enabling signal The width of the signal is the width of the enabling signal A subsystem can contain no more than one Enable block Enable r Enable Port Place this block in a subsystem to create an enabled subsystem Specifies how to handle internal states when the r Paramet arameters subsystem becomes re enabled States when enabling If checked Simulink draws the Enable block output port and outputs the enabling signal T Show output port Apply Revert Help Sample Time Determined by the signal at the enable port Vectori zed Yes Fcn Purpose Library Description Apply a specified expression to the input Nonlinear The Fcn block applies the specified C language style expression to its input The expression can be made up of one or more of these components u the input tothe block Ifu is a vector u i represents thei th element of the vector u 1 or u alone represents the first element Numeric constants Arithm
246. ivative Xd_ fult x u update Xe where x S dk Introduction Simulink partitions the state vector into two parts the continuous states and the discrete states The continuous states occupy the first part of the state vector and the discrete states occupy the second part For blocks with no states x is an empty vector Simulation Stages and S Function Routines Simulink makes repeated calls during specific stages of simulation to each block in the model directing it to perform tasks such as computing its outputs updating its discrete states or computing its derivatives Additional calls are made at the beginning and end of a simulation to perform initialization and termination tasks 8 5 8 S Functions This figure shows the order in which Simulink performs the simulation stages AR Set initial conditions gt Calculate time of next sample hit only for variable sample time blocks Y Calculate outputs y Update discrete states Y Calculate outputs e y Integration phase Calculate derivatives a a At termination perform any required tasks Simulink makes repeated calls to S function routines which perform the tasks required at each stage All the S function routines begin with the prefix md In M file S functions the S function routines are implemented as M file subfunctions In C MEX file S functions the
247. k Start 2 4 Both the outside and inside temperatures are converted from Fahrenheit to Celsius by identical subsystems Fahrenheit to Celsius conversion F2C ER PO F2C out When the heat is on the heating costs are computed and displayed on the H eat Cost Scope block Theinternal temperature is displayed on the Indoor Temp Scope block Some Things to Try Here are several things to try to see how the model responds to different parameters e Each Scope block contains a signal display area and controls that enable you to select the range of the signal displayed zoom in on a portion of the signal and perform other useful tasks The horizontal axis represents time and the vertical axis represents the signal value For more information about the Scope block see Chapter 9 The Constant block labeled Set Point at the top left of the model sets the desired internal temperature Open this block and reset the value to 80 degrees while the simulation is running See how the indoor temperature and heating costs change Also adjust the outside temperature the Avg Outdoor Temp block and see how it affects the simulation Adjust the daily temperature variation by opening the Sine Wave block labeled Daily Temp Variation and changing the Amplitude parameter What This Demo Illustrates This demo illustrates several tasks commonly used when building models e Running the simulation involves specifying
248. k over the suggestions in Some Things to Try on page 2 4 5 When you re finished running the simulation close the model by choosing Close from the File menu Description of the Demo The demo models the thermodynamics of a house using a simple model The thermostat is set to 70 degrees Fahrenheit and is affected by the outside temperature which varies by applying a sine wave with amplitude of 15 degrees to a base temperature of 50 degrees This simulates daily temperature fluctuations The model uses subsystems to simplify the model diagram and create reusable systems A subsystem is a group of blocks that is represented by a Subsystem block This model contains five subsystems one named Thermostat onenamed House and three Temp Convert subsystems two convert F ahrenheit to Celsius one converts Celsius to Fahrenheit The internal and external temperatures are fed into the House subsystem which updates the internal temperature Double click on the House block to see the underlying blocks in that subsystem Heater QDot In 1 Req Outdoor Temp the House subsystem Indoor Temp Tin Thermodynamic Model forthe House The Thermostat subsystem models the operation of a thermostat determining when the heating system is turned on and off Double click on the block to see the underlying blocks in that subsystem Ter H Blower Relay1 switch the Thermostat subsystem 2 Q uic
249. l Modeling Equations on page 3 34 describes how to build systems that model equations Editing an Existing Model To edit an existing model diagram either e Choose the Open command from the File menu then choose or enter the model file name for the model you want to edit or e Enter the name of the model without the md extension in the MATLAB command window The model must bein thecurrent directory or on the path Undoing a Command You can cancel the effects of up to 101 consecutive operations by choosing Undo from the Edit menu You can undo these operations e Adding or deleting a block e Adding or deleting a line e Adding or deleting a model annotation e Editing a block name You can reverse the effects of an Undo command by choosing Redo from the Edit menu 3 Creating a M odel Selecting Objects 3 4 Many model building actions such as copying a block or deleting a line require that you first select one or more blocks and lines objects Selecting One Object To select an object click on it Small black square handles appear at the corners of a selected block and near the end points of a selected line For example the figure below shows a selected Sine Wave block and a selected line Sine Wave When you select an object by clicking on it any other selected objects become deselected Selecting More than One Object You can select more than one object either by selecting objects one a
250. l Parameter Val ue gt BlockDefaults lt Block Parameter Name gt lt Block Parameter Val ue gt AnnotationDefaults lt Annotation Parameter Name gt lt Annotation Parameter Value gt System lt System Parameter Name gt lt System Parameter Value gt Block lt Block Parameter Name gt lt Block Parameter Val ue gt Line lt Line Parameter Name gt lt Line Parameter Val ue gt Branch lt Branch Parameter Name gt lt Branch Parameter Value gt Annotation lt Annotation Parameter Name gt lt Annotation Parameter Value gt M odel File C ontents The model file consists of sections that describe different model components e TheModel section defines model parameters e TheBl ockDef aul ts section contains default settings for blocks in the model e TheAnnotati onDef aul ts section contains default settings for annotations in the model e TheSystem section contains parameters that describe each system including the top level system and each subsystem in the model Each System section contains block line and annotation descriptions All model and block parameters are described in Appendix A The Model Section The Model section located at the top of the model file defines the values for model level parameters These parameters include the model name the version of Simulink used to last modify the model and simulation parameters The BlockDefaults Section The Bl ockDef aul ts section
251. l Simulink blocks including block callback parameters which are described in Using Callback Routines on page 3 30 Examples of commands that change these parameters follow the table Parameter Description Values Name Block s name string Type Simulink object type block read only Parent Name of the system that string owns the block BlockType Block type text BlockDescription Block description text Input Ports Array of input port locations hl vl h2 v2 Out put Ports Array of output port loca hl vl h2 v2 tions Orientation Where block faces right left down up ForegroundCol or Block name icon outline black white red green blue output signals and signal cyan magenta yellow gray label lightBlue orange darkGreen BackgroundCol or Block icon background bl ack white red green blue cyan magenta yellow gray lightBlue orange darkGreen DropShadow Display drop shadow off on NamePlacement Position of block name normal alternate Font Name Font Helvetica FontSize Font size 10 A 7 A Model and Block Parameters Table A 2 Common Block Parameters Continued Parameter Description Values Font Wei ght Font weight system dependent i ght normal demi bold FontAngle Font angle system dependent normal oblique Position Position of block in model vector left top right window NOT enclosed in quotes ShowNa me Display block
252. l ink system toa block named Scopel in theti mi ng subsystem of the engine system add_block simulink Sinks Scope engine timing Scopel This command creates a new subsystem named controller in thef14 system add block built in SubSystem Fl4 controller This command copies the built in Gain block to a block named Vol ume in the my model system and assigns the Gain parameter a value of 4 add_block built in Gain mymodel Volume Gain 4 See Also delete block set_param 11 4 add _ line Purpose Syntax Description Examples See Also Add a line to a Simulink system add line sys oport iport add_line sys points Theadd_line command adds a line to the specified system The line can be defined in two ways e By naming the block ports that are to be connected by the line e By specifying the location of the points that define the line segments add_line sys oport iport addsa straight linetoasystem fromthe specified block output port oport tothe specified block input port iport oport and iport are strings consisting of a block name and a port identifier in the form bl ock port Most block ports are identified by numbering the ports from top to bottom or from left to right such as Gai n 1 or Sum 2 Enable Trigger and State ports are identified by name such as subsystem name Enable subsystem name Trigger or IT ntegrator State add_line sy
253. lar Expansion Yes Vectorized Yes Zero Crossing Yes to detect switch on and switch off points 9 117 Repeating Sequence Purpose Library Description Wh Parameters and Dialog Box Characteristics 9 118 Generate a repeatable arbitrary signal Sources The Repeating Sequence block allows you to specify an arbitrary signal to be repeated regularly over time When the simulation reaches the maximum time value in the Time values vector the signal is repeated This block is implemented using the one dimensional Look Up Table block performing linear interpolation between points Repeating Sequence f Repeating table mask Repeating table p Parameters A vector of monotonically increasing time values The default is 0 2 Time values 02 Output values 02 A vector of output values Each corresponds to thetimevalue in the same column The default is Apply Revert Help i 0 2 Sample Time Continuous Scalar Expansion No Vectorized No Zero Crossing No Rounding Function Purpose Library Description floor f Parameters and Dialog Box Characteristics Perform a rounding function Nonlinear The Rounding Function block performs common mathematical rounding functions You can select one of these functions from the Function list floor ceil round andfix The block output is the result of the function operating on the input or inputs The name of the function
254. lared in ascending order Continuous systems have their sample time set to zero The hybrid example which starts on page 8 20 demonstrates an S function with multiple sample times Below are the S function subroutines that t i mest wo m calls Function mdllnitializeSizes initializes the states sample times state ordering strings str and sizes structure function sys x0 str ts mdll nitializeSizes Call function simsizes to create the sizes structure sizes simsizes Load the sizes structure with the initialization information sizes NumContStates 0 sizes NumDiscStates 0 sizes NumOut puts il sizes Numi nputs T sizes DirFeedthrough 0 8 13 8 S Functions 8 14 sizes NumSampl eTi mes 1 Load the sys vector with the sizes information Sys Simsizes sizes x0 No continuous states str No state ordering ts 1 0 Inherited sample time end of mdlInitialize sizes Y 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Function mdl Outputs performs the calculations Y 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 function sys mdl Outputs t x u Sys 2 u End of mdi Outputs Totest this S function in Simulink connect a sine wave generator tothe input of an S Function block Connect the output of the S F unction block to a Scope
255. lation results This option disables zero crossing detection for those blocks that have intrinsic zero crossing detection It does not disable zero crossing detection for the Hit Crossing block Improving Simulation Performance and Accuracy Improving Simulation Performance and Accuracy Simulation performance and accuracy can be affected by many things including the model design and choice of simulation parameters The solvers handle most model simulations accurately and efficiently with their default parameter values H owever some models will yield better results if you adjust solver and simulation parameters Also if you know information about your model s behavior your simulation results can be improved if you provide this information to the solver Speeding Up the Simulation Slow simulation speed can have many causes Here area few e Your model includes a MATLAB Fcn block When a model includes a MATLAB Fcn block the MATLAB interpreter is called at each time step drastically slowing down the simulation Use the built in Fcn block or Elementary Math block whenever possible Your model includes an M file S function M file S functions also cause the MATLAB interpreter to be called at each time step Consider either converting the S function to a subsystem or to a C ME X file S function Your model includes a Memory block Using a Memory block causes the variable order solvers ode15s andode113 to be reset back to order
256. lation of a next sample time depends on the input u this block has direct feedthrough Generally all blocks that use the input to calculate the next sample time flag 4 require direct feedthrough Hereis the code for the M file S function function sys x0 str ts vsfunc t x u flag This example S function illustrates how to create a variable step block in Simulink This block implements a variable step delay in which the first input is delayed by an amount of time determined by the second input dt u 2 y t dt u t switch flag case 0 sys x0 str ts mdlInitializeSizes Initialization case 2 sys md Update t x u Update Discrete states case 3 sys mdl Outputs t x u Calculate outputs case 4 sys mdl GetTimeOfNextVarHit t x u Get next sample time case 1 9 sys Unused flags 8 23 8 S Functions 8 24 otherwise error Unhandled flag num2str flag Error handling end end of vsfunc VEEE mdlInitializeSizes Return the sizes initial conditions and sample times for the S function VEEE EE function sys x0 str ts mdll nitializeSizes call simsizes for a sizes structure fill it in and convert it to a sizes array Sizes simsizes sizes NumContStates 0 sizes NumbiscStates 1 sizes NumOut puts 1 sizes Numi nputs 2 sizes DirFeedthrough 1 flag 4 requires direct feedthrough if input u is involved i
257. lation speed 4 19 MATLAB function applying to block input 9 61 9 94 Matrix Gain block 9 96 matrix writing to 9 148 maximum number of output rows 4 25 maximum order of ode15s solver 4 12 4 25 maximum step size 4 10 4 25 maximum step size parameter 4 10 mdi file 3 38 B 2 md Derivatives function 8 55 md Get Ti meOf Next Var Hi t function 8 23 mdl nitialize function 8 8 mdl nitializeConditions function 8 47 8 49 8 56 mdl I nitializeSampl eTi mes function 8 45 8 58 mdl nitializeSizes function 8 11 8 44 8 45 8 47 8 49 8 60 md Output function 8 9 8 46 md Out puts function 8 61 md Ter mi nate function 8 63 md Update function 8 9 8 45 8 46 8 47 8 64 memory and work vectors 8 48 Memory block 9 97 simulation speed 4 19 memory issues 3 33 memory region shared 9 25 9 26 9 27 memory deallocating for S function 8 63 menus 3 2 mex utility 8 2 ME X file models simulating 4 3 M file models simulating 4 3 M file S functions 8 11 simulation speed 4 19 M files running simulation from 4 3 MinMax block 9 98 zero crossings 10 6 Index mixed continuous and discrete systems 10 15 mi xedm c example 8 37 Model Browser 3 42 model files 3 38 B 2 names 3 38 Model Predictive Control Toolbox 1 7 Model section of md file B 3 Model Cl oseFcn block callback parameter 3 31 modeling equations 3 34 modeling strategies 3 33 models building 2 6 callback parameters 3 30 callback rout
258. ldren of the Unlocked subsystem in thec ut ch system find system clutch Unlocked SearchDepth 1 BlockType Goto These commands return the names of all Gain blocks in thevdp system having a Gain parameter value of 1 gb find system vdp BlockType Gain find system gb Gain 1 The above commands are equivalent to this command find_system vdp BlockType Gain Gain 1 get param set param 11 13 gcb Purpose Syntax Description Examples See Also 11 14 Get the full block path name of the current Simulink block gcb gcb sys gcb returns the full block path name of the current block in the current system gcb sys returns the full block path name of the current block in the specified system The current block is one of these During editing the current block is the block most recently clicked on During simulation of a system that contains S F unction blocks the current block is the S F unction block currently executing its corresponding MATLAB function During callbacks the current block is the block whose callback routine is being executed During evaluation of theMask nitiali zation string thecurrent block isthe block whose mask is being evaluated This command returns the path of the most recently selected block gt gt gcb ans clutch Locked Inertia This command gets the value of the Gain parameter of the current block gt gt get_param
259. le M odel in Chapter 2 Chapter 3 describes in detail how to build and edit a model It also discusses how to save and print a model and provides some useful tips Chapter 4 describes how Simulink performs a simulation It covers simulation parameters and the integration solvers used for simulation including some of 1 G etting Started 1 4 the strengths and weaknesses of each solver that should help you choose the appropriate solver for your problem It also discusses multirate and hybrid systems Chapter 5 discusses Simulink and MATLAB features useful for viewing and analyzing simulation results Chapter 6 discusses methods for creating your own blocks and using masks to customize their appearance and use Chapter 7 describes subsystems whose execution depends on triggering signals Chapter 8 describes how to create blocks using M files or C ME X files Chapter 9 provides reference information for all Simulink blocks Chapter 10 provides information about how Simulink works including information about zero crossings algebraic loops and discrete and hybrid systems Chapter 11 provides reference information for commands you can use to create and modify a model from the MATLAB command window or from an M file Appendix A lists model and block parameters This information is useful with theget paramandset_ param commands described in Chapter 11 Appendix B describes the format of the file that stores model information
260. le defines a sample time for a block that is continuous in nature Initialize the sample time and offset static void mdlIlnitializeSampleTimes SimStruct 5 ssSetSampleTime S 0 CONTINUOUS SAMPLE TI ME ssSetOffsetTime S 0 0 0 W riting S Functions as C M EX iles The following statement also appears in the md I ni ti alizeSizes function ssSetNumSampleTimes S 1 Example Defining a Sample Time for a Hybrid Block This example defines sample times for a hybrid S F unction block Initialize the sample time and offset static void mdllnitializeSampleTi mes SimStruct S Continuous state sample time and offset ssSetSampleTime S 0 CONTINUOUS SAMPLE TI ME ssSetOffsetTime S 0 0 0 Discrete state sample time and offset ssSetSampleTime S 1 0 1 ssSetOffsetTime S 1 0 025 The offset causes Simulink to call themd Update function at these times 0 025 seconds 0 125 seconds 0 225 seconds and so on in increments of 0 1 seconds The following statement which indicates how many sample times are defined also appears in the md ni tializeSizes function ssSetNumSampleTimes S 2 Setting the Initial Conditions The initial conditions for the S F unction block s states are defined in the mdli nitializeConditions function Thex0 vector contains the initial conditions Simulink calls mdi nitializeConditions once during the simulation to set the initial conditi
261. le must contain a matrix of two or more rows The first row must contain monotonically increasing time points Other rows contain data points that correspond to the time point in that column The matrix is expected to havethis form ty t2 tinal ul ul Ulsnal un un UNfinal The width of the output depends on the number of rows in the file The block uses thetime data to determine its output but does not output the time values This means that in a matrix containing m rows the block outputs a vector of length m 1 consisting of data from all but the first row of the appropriate column If an output value is needed at a time that falls between two values in the file the value is linearly interpolated between the appropriate values If the required time is less than the first time value or greater than the last time value in the file Simulink extrapolates using the first two or last two points to compute a value If the matrix includes two or more columns at the same time value the output is the data point for the first column encountered For example for a matrix that has this data time values 0122 data points 23 45 At time 2 the output is 4 the data point for the first column encountered at that time value From File Parameters and Dialog Box Characteristics Simulink reads the file into memory at the start of the simulation As a result you cannot read data from the same file named in a To File block in th
262. le step solvers can modify their step sizes during the simulation They provide error control and zero crossing detection Fixed step solvers take the same step size during the simulation They provide no error control and do not locate zero crossings For a thorough discussion of solvers see Using MATLAB 4 7 4 Running a Simulation Default solvers f you do not choose a solver Simulink chooses one based on whether your model has states e f the model has continuous states ode 45 is used ode45 is an excellent general purpose solver However if you know that your system is stiff and if ode45 isnot providing acceptable results tryode15s For a definition of stiff see the note on the next page e Ifthe model has no continuous states Simulink uses the variable step sol ver calleddiscrete and displays a message indicating that it isnot usingode45 Simulink also provides a fixed step solver called di screte This model shows the difference between the twodiscrete solvers z Out Sine Wave Unit Delay Ts 05 a 1 5 z Out Sine Wave1 Unit Delay1 Ts 0 75 With sample times of 0 5 and 0 75 the fundamental sampletimefor the model is 0 25 seconds The difference between the variable step and the fixed step discrete solvers is the time vector that each generates The fixed step discrete solver generates this time vector 0 0 0 25 0 5 0 75 1 0 1 25 The variable step discrete solver generates this time vector 0 0 O
263. licking on the block Change the Number of inputs parameter 2 Q uick Start 2 10 value to 2 then click on the Close button Simulink adjusts the number of input ports Mus Combine scalar or vector signals into larger vectors Parameters Number of inputs Apply Revert Help Now it s time to connect the blocks Connect the Sine Wave block to the top input port of the Mux block position the pointer over the output port on the right side of the Sine Wave block Notice that the cursor shape changes to cross hairs Sine Wave 1 Mux s Scope Integrator Hold down the mouse button and move the cursor to the top input port of the M ux block Notice that the line is dashed while the mouse button is down and that the cursor shape changes to double lined cross hairs as it approaches the Mux block oe 4 Sine Wave 1 p Integrator Now release the mouse button The blocks are connected You can also connect the line to the block by releasing the mouse button while the pointer is inside the icon If you do the line is connected to the input port closest to the cursor s position me f Sine Wave 1 Mux s Scope Integrator Building a Simple M odel If you look again at the model on page 2 6 you ll notice that most of the lines connect output ports of blocks to input ports of other blocks However one line c
264. ll Simulink uses different symbols on the Trigger and Subsystem blocks to indicate rising and falling triggers or either This figure shows the trigger symbols on Subsystem blocks Select the trigger type from these choices Subsystem with Subsystem with Subsystem with Rising trigger Falling trigger Rising or Falling trigger 7 9 7 Conditionally Executed Subsystems 7 10 Outputs and States between Trigger Events Unlike enabled subsystems triggered subsystems always hold their outputs at the last value between triggering events Also triggered subsystems cannot reset their states when triggered states of any discrete blocks are held between trigger events O utputting the Trigger Control Signal An option on the Trigger block dialog box lets you output the trigger control signal To output the control signal select the Show output port check box Trigger Trigger Port Place this block in a subsystem to create a triggered subsystem Parameters rising re Select this check box to show the output port Trigger type Apply Revert Help Close Function Call Subsystems You can create a triggered subsystem whose execution is determined by logic internal to an S function instead of by the value of a signal These subsystems are called functi on call subsystems For more information about function call subsystems see U sing F unction Call Subsystems on page 8 51
265. ller synthesis with a mix of H infinity LQG and pole placement objectives The Model Predictive Control Toolbox The Model Predictive Control Toolbox was written by Manfred Morari and N Lawrence Ricker Model predictive control is especially useful for control applications with many input and output variables many of which have constraints As a result it has become particularly popular in chemical engineering and other process control applications The Mu Analysis and Synthesis Toolbox TheMu Analysis and Synthesis Toolbox by Gary Balas Andy Packard J ohn Doyle Keith Glover and Roy Smith contains specialized tools for H optimal control and u analysis and synthesis an approach to advanced robust control design of multivariable linear systems The NAG Foundation Toolbox The NAG Foundation Toolbox includes more than 200 numeric computation functions from the well regarded NAG Fortran subroutine libraries It provides specialized tools for boundary value problems 1 G etting Started 1 8 optimization adaptive quadrature surface and curve fitting and other applications The Neural Network Toolbox The Neural Network Toolbox by Howard Demuth and Mark Bealeis a collection of MATLAB functions for designing and simulating neural networks Neural networks are computing architectures inspired by biological nervous systems that are useful in applications where formal analysis is extremely difficult or impossible such as pattern
266. lock the string K is displayed To be ableto modify the gain during a simulation using a slider control usethe Slider Gain block described on page 9 136 r Gain Scalar or vector gain y k u p Parameters Gain 1 Apply Revert Help u Direct Feedthrough Yes The gain specified as a scalar vector variable name or expression The default is 1 Sample Time Inherited from driving block Scalar Expansion Of input and Gain parameter States 0 Vectorized Yes Zero Crossing No Goto Purpose Library Description Pass block input to From blocks Connections The Goto block passes its input to its corresponding From blocks From and Goto blocks allow you to pass a signal from one block to another without actually connecting them A Goto block can pass its input signal to more than one From block although a From block can receive a signal from only one Goto block The input to that Goto block is passed to the From blocks associated with it as though the blocks were physically connected F or limitations on the use of From and Goto blocks see the description of the From block on page 9 64 Goto blocks and From blocks are matched by the use of Goto tags defined as the Tag parameter The Tag visibility parameter determines whether the location of From blocks that access the signal is limited local the default means that From and Goto blocks using the tag must be in the same subsystem A local
267. locks having constant sample time must generate their output at the model s effective sample time Because of this feature all blocks compute their output at each sample time hit or in the case of purely continuous systems at every simulation step For blocks having constant sample time whose parameters do not change during a simulation evaluating these blocks during the simulation is inefficient and slows down the simulation You can set the nvari ant Constants parameter to remove all blocks having constant sample times from the simulation loop The effect of this feature is twofold first parameters for these blocks cannot be changed duringa 10 9 10 Additional Topics 10 10 simulation and second simulation speed is improved Thespeed improvement depends on model complexity the number of blocks with constant sample time and the effective sampling rate of the simulation You can set the parameter for your model by entering this command set_param model_name InvariantConstants on You can turn off the feature by issuing the command again assigningthe parameter the valueof off You can determine which blocks have constant sample time by selecting Sample Time Colors from the Format menu Blocks having constant sample time are colored magenta Discrete Time Systems Discrete Time Systems Simulink has the ability to simulate discrete sampled data systems Models can be multirate that is they c
268. lt the block can be useful in models intended to run for an indefinite length of time such as in vibration or fatigue testing The incremental algorithm computes the sine based on the value computed at the previous sample time This method makes use of the following identities sin t At sin t cos At sin At cos t cos t At cos t cos At sin t sin At Sine Wave These identities can be written in matrix form sin t At _ cos At sin At sin t cos t At sin At cos At cos t Since At is constant the following expression is a constant cos At sin At sin At cos At Therefore the problem becomes one of a matrix multiply of the value of sin t by a constant matrix to obtain sin t At This algorithm may also be faster on computers that do not have hardware floating point support for trigonometric functions Using the Sine Wave Block in Continuous Mode A Sample time parameter value of zero causes the block to behave in continuous mode When operating in continuous mode the Sine Wave block can become inaccurate due to loss of precision as time becomes very large Parameters ime Wave and Dialog Be Pupe a ene neve The amplitude of the signal The default is 1 Box m Parameters Aa The frequency in radians second The default is 1 Frequency rad sec rad sec 1 Bh The phase shift in radians The default is 0 jase rad 0 radians Sample time i 0 The sample period
269. lue of 1 at that time step If the input signals at two adjacent points bracket the offset value but neither value is exactly equal to the offset the block outputs a value of 1 at the second time step If the Show output port check box is not selected the block ensures that the simulation finds the crossing point but does not generate output The Hit Crossing block serves as an Almost Equal block useful in working around limitations in finite mathematics and computer precision Used for these reasons this block may be more convenient than adding logic to your model to detect this condition Thehardstop andcl ut ch demos illustratethe use of the Hit Crossing block In thehardstop demo the Hit Crossing block is in the Friction Model subsystem In thecl utch demo the Hit Crossing block is in the Lockup Detection subsystem Hit Crossing r Hit Crossing Forces simulation to locate hit zero crossing of the input signal Outputs 1 when hit crossing is detected otherwise outputs 0 The value whose crossing is to be detected Parameters The direction from which the input signal approaches the hit crossing offset for a crossing to be detected Hit crossing offset Hit crossing direction IV Show output port Whether to draw an output port Apply Revert Help 9 75 Hit Crossing 9 76 Characteristics Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Ye
270. m find_system 11 23 simulink Purpose Open the Simulink block library Syntax si mul i nk Description Thesi mul i nk command opens the Simulink block library window and creates and displays a new empty model window except in these cases e f a model window is open Simulink does not create a new model window e If the Simulink block library window is already open issuing this command makes the Simulink window the active window 11 24 Model and Block Parameters Introduction 2 A 2 Model Parameters A 3 Common Block Parameters A 7 Block Specific Parameters A 10 Mask Parameters 8 A 23 A Model and Block Parameters Introduction This appendix lists model block and mask parameters Thetables that list the parameters provide enough information to enable you to modify models from the command line using thes et _ param command described in Chapter 11 M odel Parameters Model Parameters This table lists and describes parameters that describe a model The parameters appear in the order they are defined in the model file described in Appendix B The table also includes model callback parameters described in Using Callback Routines on page 3 30 The Description column indicates where you can set the value on the Simulation Parameters dialog box Model parameters that are simulation parameters are described in more
271. mNonsampl edZCs S num Then define the md ZeroCrossings routine to return the nonsampled zero crossings sf un_zc c shows how to use nonsampled zero crossings W riting S Functions as C M EX iles Mode Work Vector Simulink supports a work vector referred to as the mode vector Elements are integer values that are typically used with nonsampled zero crossings Specify the number of mode vector elements in mdi I nitializeSizes using ss Set NumModes S num You can then access the mode vector using ssGetModeVector Output and Work Vector Widths For S functions with dynamically sized inputs and outputs you can configure your output width to be a function of your input width and vice versa To do this define these routines int mdi GetInputPortWidth int outputWidth return input width int mdi GetQutputPortWidth int inputWidth return output width Also you can configure your work vector widths based on the input width output width or sample times To do this define a md Set Work Wi dt hs routine sfun_dynsize c demonstrates how tousethemd Seti nputPort Width mdi Set Out put Port Width and mdi Set Work Wi dths optional methods to configure the input port width output port width and real work vector length based on the size of the signal driving the S function Removing Ports When No Inputs and or Outputs Any C MEX Fortran MEX or M file S function that indicates it has no input and or outputs will have
272. mbolic Math Toolbox gives MATLAB an integrated set of tools for symbolic computation and variable precision arithmetic based on Maple V The Extended Symbolic Math Toolbox adds support for Maple programming plus additional specialized functions The System Identification Toolbox The System Identification Toolbox written by Lennart Ljung is a collection of tools for estimation and identification System identification is a way tofind a mathematical model for a physical system like an electric motor or even a financial market based only on a record of the system s inputs and outputs The Wavelet Toolbox The Wavelet Toolbox provides a comprehensive collection of routines for examining local multiscale or nonstationary phenomena Wavelet methods offer additional insight and performance in any application where Fourier techniques have been used The toolbox is useful in many signal and image processing applications including speech and audio processing communications geophysics finance and medicine 1 9 1 G etting Started The Simulink Real Time Workshop 1 10 The Simulink Real Time Workshop automatically generates C code directly from Simulink block diagrams This allows the execution of continuous discrete time and hybrid system models on a wide range of computer platforms including real time hardware Simulink is required The Real Time Workshop can be used for Rapid Prototyping As a rapid prototyping tool the
273. ments Parameters The order that the input elements are to appear ARNIR in the output vector 3 The number of elements in the input vector Apply Revert Help Characteristics Sample Time Inherited from driving block Vectori zed Yes 9 128 S Function Purpose Library Description system f Parameters and Dialog Box Access an S function Nonlinear The S Function block provides access to S functions from a block diagram The S function named as the S function name parameter can be an M file or MEX file written as an S function The S F unction block allows additional parameters to be passed directly to the named S function The function parameters can be specified as MATLAB expressions or as variables separated by commas For example A B C D eye 2 2 zeros 2 2 Note that although individual parameters can be enclosed in square brackets the list of parameters must not be enclosed in square brackets The S function block displays the name of the specified S function and is always drawn with one input port and one output port regardless of the number of inputs and outputs of the contained subsystem Vector lines are used when the S function contains more than one input or output The input vector width must match the number of inputs contained in the S function Theblock directs thefirst element of the input vector tothe first input of the S function the second element to the second input and so o
274. mes mdl I nitializeConditions Calculation of outputs md Outputs U pdate of discrete states md Update Calculation of next sample hit optional mdl Get Ti meOf Next VarHit Calculation of derivatives md Derivatives Perform tasks at end of simulation mdi Terminate Unlike M file S functions there is not an explicit f ag parameter associated with each S function routine This is because Simulink automatically calls each S function routine at the appropriate time in the simulation stage Also there are S function routines associated with C ME X fileS functions that don t have counterparts in M file S functions These include mdl I nitializeSampleTimes andmdllnitializeConditions 8 26 W riting S Functions as C MEX Files Simulink maintains information about the S F unction block in a data structure called the Si mStruct Theinclude filethat defines the Si mStruct provides macros that enable your ME X file to set values in and get values from thesi mStr uct The statement that includes the definition of theSi mStruct is shown in Statements Required at the Top of the File on page 8 27 The macros that access theSi mStruct are listed in Appendix C Simulink provides a template C ME X file S function that includes the statements that define the necessary functions as well as comments that should help you write the code needed for your S function block This template file sf unt mp c can be found in the directory si
275. meters except Buffer size Vectorized Yes Zero Crossing No 9 161 Width Purpose Library Description a Parameters and Dialog Box Characteristics 9 162 Output the width of the input vector Connections The Width block generates as output the width of its input vector Width Outputs the width of the input signal Help IE Sample Time Constant Vectori zed Yes XY Graph Purpose Library Description Parameters and Dialog Box Characteristics Display an X Y plot of signals using a MATLAB figure window Sinks The XY Graph block displays an X Y plot of its inputs in a MATLAB figure window The block has two scalar inputs The block plots data in the first input the x direction against data in thesecond input the y direction This block is useful for examining limit cycles and other two state data Data outside the specified range is not displayed Simulink opens a figure window for each XY Graph block in the model at the start of the simulation For a demo that illustrates the use of the XY Graph block enter orenzs inthe command window r XY scope mask used as time base Enter plotting ranges Parameters x min 1 max 1 ymin 1 ymax 1 Sample Time 1 Apply Revert Help i XY scope using MATLAB graph window First input is Sample Time States The minimum x axis value The default is 1 The maximum x axis value The d
276. ml Work S 0 number of integer work vector elems ssSetNumPWork S 0 number of pointer work vector el ems mdl I nitializeSampleTimes initialize sample times array static void mdl Il nitializeSampleTimes SimStruct S ssSetSampleTime S 0 1 0 ssSetOffsetTime S 0 0 0 mdlInitializeConditions initialize the states static void mdllnitializeConditions double x0 SimStruct S int i for i 0 i lt 2 x0t 1 0 i mdl Outputs compute the outputs static void mdl Outputs double y const double xx const double u SimStruct S int tid y Cx Du y 0 C O 0 x 0 C 0 1 x 1 D 0 0 u 0 D 0 1 u 1 y 1 CLI 0 ex 0 CL 1 1 x 1 DL 1 0 sul 0 D 1 1 ul 1 mdi Update perform action at major integration time step static void mdl Update double x const double u SimStruct S int tid double tempX 2 xdot Ax Bu tempX 0 A 0O 0 x 0 A 0 1 x 1 B 0 0 u 0 B 0 1 u 1 tempX 1 A 1 0 x 0 A 1 1 x 1 B 1 0 u 0 B 1 1 u 1 8 36 W riting S Functions as C M EX iles x 0 tempX 0 x 1 tempX 1 mdi Derivatives compute the derivatives static void mdIDerivatives double dx const double xx const double u SimStruct S int tid mdi Terminate called when the simulation is terminated static void mdl Terminate SimStruct S
277. mmand replaces the Gain blocks in thef 14 system with Integrator blocks but does not display the dialog box replace _block f14 Gain Integrator noprompt find _system set_param save_system Purpose Syntax Description Example See Also Save a Simulink system Save system save _system sys save_system sys newname save_systemsavesthe current top level system toa file with its current name save_system sys Saves the specified top level system to a file with its current name The system must be open save _system sys newname Saves the specified top level system toa file with the specified new name The system must be open This command saves the current system Save system This command saves thevdp system Save system vdp This command saves thevdp system toa file with the name myvdp Save system vdp myvdp close system new_system open_system 11 21 set param Purpose Syntax Description Examples 11 22 Set Simulink system and block parameters set _param obj parameterl valuel parameter2 value2 set _param obj parameterl valuel parameter2 value2 where obj is a system or block path sets the specified parameters to the specified values Case is ignored for parameter names Value strings are case sensitive Any parameters that correspond to dialog box entries have string values Model and block parameters are listed in Appendix A
278. model equations Converting Celsius to Fahrenheit To model the equation that converts Celsius temperature to Fahrenheit Tr 9 5 Tc 32 First consider the blocks needed to build the model e A Ramp block to input the temperature signal from the Sources library e A Constant block to define a constant of 32 also from the Sources library e A Gain block to multiply the input signal by 9 5 from the Linear library e A Sum block to add the two quantities also from the Linear library e A Scope block to display the output from the Sinks library Next gather the blocks into your model window 4 gt Mm Ramp Gain Sum Scope Constant Assign parameter values tothe Gain and Constant blocks by opening double clicking on each block and entering the appropriate value Then click on the Close button to apply the value and dosethe dialog box Now connect the blocks Constant Modeling Equations The Ramp block inputs Celsius temperature Open that block and change the Initial output parameter to 0 The Gain block multiplies that temperature by the constant 9 5 The Sum block adds the value 32 tothe result and outputs the Fahrenheit temperature Open the Scope block to view the output Now choose Start from the Simulation menu to run the simulation The simulation will run for 10 seconds Modeling a Simple Continuous System To model the differential equation x t 2x t u t where u
279. mpts and associates variables with those prompts The Initialization Page Masked blocks cannot access the base workspace or other mask workspaces The contents of a mask workspace include the variables associated with the mask s parameters and variables defined by initialization commands The variables in the mask workspace can be accessed by the masked block If the block is a subsystem they can also be accessed by all blocks in the subsystem Mask workspaces are analogous to the local workspaces used by M file functions Y ou can think of the expressions entered into the dialog boxes of the underlying blocks and the initialization commands entered on the Mask Editor as lines of an M file function Using this analogy the local workspace for this function is the mask workspace Inthem b example described earlier in this chapter the Mask Editor explicitly creates m andb in the mask workspace by associating a variable with a mask parameter However variables in the mask workspace are not explicitly assigned to blocks underneath the mask Instead blocks beneath the mask have access to all variables in the mask workspace It may be instructive to think of the underlying blocks as looking into the mask workspace The figure below shows the mapping of values entered in the mask dialog box to variables in the mask workspace indicated by the solid line and the access of those variables by the underlying blocks indicated by t
280. multiple rates Similarly Subsystem blocks that contain blocks with differing sample times are also colored as hybrids because there is no single rate associated with them If all of the blocks within a subsystem run at a single rate then the Subsystem block is colored according to that rate Discrete Time Systems Under some circumstances Simulink also backpropagates sample times to source blocks if it can do so without affecting the output of a simulation For instance in the model below Simulink recognizes that the Signal Generator is driving a Discrete Time Integrator so it assigns the Signal Generator and the Gain block the same sample time as the Discrete Time I ntegrator block oooo T oo z 1 Signal Discrete Time Gain Generator Integrator You can verify this by enabling Sample Time Colors and noting that all blocks are colored red Because the Discrete Time Integrator block only looks at its input at its sample times this change does not affect the outcome of the simulation but does result in a performance improvement Replacing the Discrete Time Integrator block with a continuous Integrator block as shown below and recoloring the model by choosing Update Diagram from the Edit menu cause the Signal Generator and Gain blocks to change to continuous blocks as indicated by their being colored black oooo 1 00 5 Signal Integrator Gain Generator Mixed Continuous and Discrete Systems Mixed continuous and disc
281. my mode system The block is 75 pixels wide by 25 pixels high The position vector is not enclosed in quotes set _param mymodel Gain Position 50 250 125 275 A Model and Block Parameters Block Specific Parameters These tables list block specific parameters for all Simulink blocks When setting block parameters with thes et _ param command you identify the block by specifying itsBl ockType parameter TheBl ockType appears in parentheses after the block name The table includes detailed information only for built in blocks not for masked blocks although the table includes the Mas kType parameter value for masked blocks For more information see Mask Parameters on page A 23 The Dialog Box Prompt column indicates the text of the prompt for the parameter on the block s dialog box The Values column shows the type of value required scalar vector variable the possible values Separated with a vertical line and the default value enclosed in braces Table A 3 Connections Library Block Parameters Block BlockType Parameter Dialog Box Prompt Values Data Store Memory Dat aSt or eMemor y Dat aStoreName Data store name tag A Initial Value Initial value vector 0 Data Store Read Dat aStoreRead Dat aSt oreName Data store name tag A Sampl eTi me Sample time scalar sample period 1 or vector period offset Data Store Write Dat aStoreWrite Dat aStoreName Data store name tag A Sampl e
282. n calculating the next sample time hit sizes NumSampleTimes 1 sys simsizes sizes Initialize the initial conditions x0 0 Set str to an empty matrix str Initialize the array of sample times ts 2 0 variable sample time end of mdlInitializesizes W riting S Functions as M Files md Update Handle discrete state updates sample time hits and major time step requirements OsSssseesssnssessssaasesesssssssssssssssssssesssssessssssssesscss function sys mdl Update t x u sys u l end of mdi Update mdi Outputs Return the block outputs function sys mdl Outputs t x u sys x 1 end mdi Out puts VEREER mdi GetTi meOf Next VarHit Return the time of the next hit for this block Note that the result is absolute time Oesescscssse esses essa sess ssssssssssseesessssssssssssessssssessss function sys mdi GetTi meOf Next VarHit t x u sys t u 2 end of mdi GetTi meOf Next VarHit md Get Ti meOf Next Var Hit returns the time of the next hit the time in the simulation when vsf unc is next called This means that thereis no output from this S function until the time of the next hit Invs func thetime of the next hit issettot u 2 which means that the second input u 2 sets the time when the next call tovsfunc occurs Passing Additional Parameters Simulink always passest x and u into S functions It
283. n Likewise the output vector width must match the number of S function outputs r Function User definable block Blocks may be written in M C or Fortran and must conform to S function standards tx u and flag are automatically passed to the S function by SIMULINK Extra parameters may be specified in the S function parameters field Parameters S function name system The S function name S function parameters Apply Revert Help Additional S function parameters 9 129 S Function Characteristics 9 130 Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Depends on contents of S function Depends on contents of S function Depends on contents of S function Depends on contents of S function No Sign Purpose Library Description EE Dialog Box Characteristics Indicate the sign of the input Nonlinear The Sign block indicates the sign of the input e The output is 1 when the input is greater than zero e The output is O when the input is equal to zero e The output is 1 when the input is less than zero m Signum Outputs 1 for positive input 1 for negative input and 0 for O input y signumlu ply Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion N A Vectorized Yes Zero Crossing Yes to detect when the input crosses through zero 9 131 Signal
284. n output that is symmetric about Zero y q round u q wherey isthe output u theinput and q the Quantization interval parameter Quantizer r Quantizer Discretize input at given interval The interval around which the output is quantized Permissible output values for the Quantizer block aren q wheren is an integer andq the Quantization interval Thedefaultis Parameters Quantization interval Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion Of parameter Vectorized Yes Zero Crossing No 9 109 Ramp Purpose Library Description L4 Parameters and Dialog Box Characteristics 9 110 Generate constantly increasing or decreasing signal Sources The Ramp block generates a signal that starts at a specified time and value and changes by a specified rate r Ramp mask ramp The rate of change of the generated signal The default is 1 r Parameters Slope in The time at which the signal begins to be generated The default is 0 Start time 0 Initial output 0 Apply Revert Help The initial value of the signal The default is 0 Sample Time Inherited from driven block Scalar Expansion Yes Vectorized Yes Zero Crossing Yes Random Number Purpose Library Description ma Parameters and Dialog Box Characteristics Generate normally distributed random numbers Sources The Random Number
285. n 11 22 Connections library A 10 copying 3 6 3 7 Discrete library A 12 evaluating 10 2 Linear library A 14 modifying 4 2 Nonlinear library A 16 prompts 6 10 scalar expansion 3 11 3 12 Sinks library A 19 Sources library A 21 specifying 2 9 3 7 adding to model 11 4 alignment 3 6 callback parameters 3 31 callback routines 3 30 connecting 2 10 3 17 connections checking 10 2 copying from block library 2 7 copying from block library 2 7 3 14 copying into models 3 6 copying to other applications 3 7 current 11 14 deleting 3 8 11 10 disconnecting 3 10 discrete 10 11 drop shadows 3 12 duplicating 3 7 grouping to create subsystem 3 28 handle of current 11 15 library 3 13 manipulating with mouse and keyboard 3 25 moving between windows 3 7 moving in a model 2 9 3 7 orientation 3 8 path 11 3 reference 3 13 3 14 replacing 11 20 resizing 3 9 reversing signal flow through 3 35 signal flow through 3 8 under mask 6 9 updating 10 2 updating from library 3 15 vectorization 3 11 Index blocksets DSP Blockset 1 14 Fixed Point Blockset 1 14 Nonlinear Control Design Blockset 1 15 Blocksets and Toolboxes library 9 3 bode function 5 11 Bogacki Shampine formula 4 9 4 10 Boolean expressions modeling 9 20 bounding box grouping blocks for subsystem 3 28 selecting objects 3 5 branch lines 3 18 3 35 Break Library Link menu item 3 16 breaking link to library block 3 15 Browser 3 42 building models exercise 2 6 tips 3 3
286. na Save options T Limit rows to last 1000 Decimation DO Apply Beven Help Close Loading Input from the Base Workspace Inport blocks in the top level of the model provide the means of supplying inputs from outside the system These external inputs can be specified either as a MATLAB command expressed in terms of simulation time t or as a matrix that provides input values for all the Inport blocks Y ou specify external input by selecting the Input check box in the Load from workspace area of this dialog box page You provide external inputs using a MATLAB command by specifying the command as a string At each time point in the simulation MATLAB evaluates the string the result is the input You can specify multiple external inputs by separating the expressions with a comma For example sin t inputs sin t at each time step sin t cos t provides two external inputs at each time step You can provide a matrix of time and input values The first column must be a vector of times in ascending order The remaining columns are interpreted as input values where each column represents the input for a different Inport block in sequential order and each row is the input value for the The Simulation Parameters Dialog Box corresponding time point When simulation times do not match the time values included in the time vector Simulink linearly interpolates for the time and input values This is the same method used for t
287. name on off Tag User defined string 2 UserData Any MATLAB datatype not saved in the md file Seleted Block selected state on off Closefen Close callback MATLAB expression CopyFen Copy callback MATLAB expression DeleteFcn Delete callback MATLAB expression nitFen Initialization callback MATLAB expression Loadfen Load callback MATLAB expression odel CloseFcn ameChangeFcn OpenFcn ParentCloseFcn PreSaveFcn PostSavefen StartFen Model close callback Block name change callback Open callback Parent subsystem close call back Pre save callback Post save call back Start simulation callback MATLAB expression MATLAB expression MATLAB expression MATLAB expression MATLAB expression MATLAB expression MATLAB expression Common Block Parameters Table A 2 Common Block Parameters Continued Parameter Description Values StopFen Termination of simulation MATLAB expression callback UndoDel eteFcn Undo block delete callback MATLAB expression These examples illustrate how to change these parameters This command changes the orientation of the Gain block in the my mode system so it faces the opposite direction right to left set_param mymodel Gain Orientation left This command associates an OpenFcn callback with the Gain block in the my model system set_param mymodel Gain OpenFcn my_open_cb This command sets the Posi ti on parameter of the Gain block in the
288. nce block with an unresolved link e When you query the Li nkSt atus parameter of a block usingtheset_param command see the next section e When you use thefind_ system command Breaking a Link to a Library Block You can break the link between a reference block and its library block to cause the reference block to become a simple copy of the library block unlinked tothe library block Changes to the library block no longer affect the block Breaking links tolibrary blocks enables you to transport a model as a stand alone model without the libraries 3 15 3 Creating a M odel 3 16 To break the link between a reference block and its library block select the block then choose Break Library Link from the Edit menu You can also break the link between a reference block and its library block from the command line by changing the value of the LinkStatus parameter to none using this command set _param refblock LinkStatus none You can savea system and break all links between reference blocks and library blocks using this command Save _system sys newname Breaklinks Finding the Library Block for a Reference Block To find the source library and block linked to a reference block select the reference block then choose Go To Library Link from the Edit menu If the library is open Simulink selects the library block displaying selection handles on the block and makes the source library the active window If
289. nd is evaluated in MATLAB before assignment and the value entered in the second field is assigned to variable b and is stored as a literal which means that its value is the string entered in the dialog box The Control type field values for all dialog box parameters are stored in the MaskStyleString parameter as a string with individual values separated by a comma The Popup strings values appear after the popup type as shown in this example edit checkbox popup red bl ue green e The parameter values are stored in the Mas kVal ueString mask parameter as a string with individual values separated by a vertical bar The order of the values is the same as the order the parameters appear on the dialog box M ask Parameters For example these statements define values for the parameter field prompts and the values for those parameters MaskPromptString Slope Intercept MaskValueString 215 A 25 A Model and Block Parameters A 26 Model File Format Model File Contents The Model Section The BlockDefaults Section The AnnotationDefaults Section The System Section A Sample Model File B M odel File Format Model File Contents A model file is a structured ASCII file that contains keywords and parameter value pairs that describe the model The file describes model components in hierarchical order The structure of the model file is Model lt Model Parameter Name gt lt Mode
290. nd zeros Linear The Zero Pole block implements a system with the specified zeros poles and gain in terms of the Laplace operator s A transfer function can be expressed in factored or zero pole gain form which for a single input single output system in MATLAB is _ 2s _ o S Z DX S Z 2 S Z m H Keay 8 S PCyS P 2 P where Z represents the zeros vector P the poles vector and K the gain Z can be a vector or matrix P must be a vector K can be a scalar or vector whose length equals the number of rows in Z The number of poles must be greater than or equal to the number of zeros If the poles and zeros are complex they must be complex conjugate pairs Block input and output widths are equal to the number of rows in the zeros matrix The Zero Pole Block Icon The Zero Pole block displays the transfer function in its icon depending on how the parameters are specified e f each is specified as an expression or a vector the icon shows the transfer function with the specified zeros poles and gain If you specify a variable in parentheses the variable is evaluated For example if you specify Zeros as 3 2 1 Polesas poles wherepol es is defined in the workspace as 7 5 3 1 and Gain as gain the icon looks like this gain s 3 s 2XNs 1 S7 S 5 s 3Ys 1 e f each is specified as a variable the icon shows the variable name followed by s if appropriate For example if you specify Zer
291. ndition port causing an algebraic loop For an example of this situation see the bounce model e When you want to pass the state from one conditionally executed subsystem to another which may cause timing problems For an example of this situation see thec ut ch model 9 81 Integrator 9 82 You can correct these problems by passing the state through the state port rather than the output port Although the values are the same Simulink generates them at slightly different times which protects your model from these problems Y ou output the block state by selecting the Show state port check box By default the state port appears on the top of the block as shown in this figure Integrator Limiting the Integral To prevent the output from exceeding specifiable levels select the Limit output check box and enter the limits in the appropriate parameter fields Doing so causes the block to function as a limited integrator When the output is outside the limits the integral action is turned off to prevent integral wind up During a simulation you can change the limits but you cannot change whether the output is limited The output is determined as follows When the integral is less than the Lower saturation limit and the input is negative the output is held at the Lower saturation limit When the integral is between the Lower saturation limit and the Upper saturation limit the output is the integral When the integral is g
292. ne then type label Double click on line then type label Option drag label Ctrl drag label Drag label Drag label Click in label then edit Click in label then edit Shift click on label then press Delete Shift click on label then press Delete The next table lists mouse and keyboard actions that apply to annotations Creating Subsystems Table 0 4 Mouse and Keyboard Actions that Manipulate Annotations Action Microsoft Windows Macintosh X Windows Create annotation Double click in Double click in Double click in diagram then type diagram then type diagram then type text text text Copy annotation Ctrl drag label Option drag label Ctrl drag label Move annotation Drag label Drag label Drag label Edit annotation Delete annotation Click in text then edit Click in text then edit Click in text then edit Shift select Shift select Shift select annotation then annotation then annotation then press Delete press Delete press Delete Creating Subsystems As your model increases in size and complexity you can simplify it by grouping blocks into subsystems Using subsystems has these advantages e t helps reduce the number of blocks displayed in your model window e t allows you to keep functionally related blocks together e t enables you to establish a hierarchical block diagram where a Subsystem block is on one layer and the blocks that make up the subsystem are on anothe
293. nections library contains blocks that allow multiplexing and demultiplexing implement external Input Output pass data to other parts of the model create subsystems and perform other functions e The Blocksets and Toolboxes library contains the Extras block library of specialized blocks e The Demos library contains useful MATLAB and Simulink demos Table 9 1 Sources Library Blocks Block Name Purpose Band Limited White Noise Introduce white noise into a continuous system Chirp Signal Generate a sine wave with increasing frequency Clock Display and provide the simulation time Constant Generate a constant value Digital Clock Generate simulation time at the specified sampling interval Digital Pulse Generator Generate pulses at regular intervals From File Read data from a file From Workspace Pulse Generator Ramp Read data from a matrix defined in the workspace Generate pulses at regular intervals Generate a constantly increasing or decreasing signal 9 3 9 Block Reference Table 9 1 Sources Library Blocks Continued Block Name Purpose Random Number Repeating Sequence Signal Generator Sine Wave Step Uniform Random Number Generate normally distributed random numbers Generate a repeatable arbitrary signal Generate various waveforms Generate a sine wave Generate a step function Generate uniformly distributed random numbers Table 9 2 Sinks Library Blocks
294. nitial conditions on the block dialog box or as input to the block e Output the state e Define upper and lower limits on the integral e Reset the state depending on an additional reset input These features are described below Integration Methods The block can integrate using these methods F orward Euler Backward Euler and Trapezoidal For a given step k Simulink updates y k andx k 1 T is the sampling period delta T in the case of triggered sampling time Values are clipped according to upper or lower limits In all cases x 0 C clipped if necessary e Forward Euler method the default also known as Forward Rectangular or left hand approximation For this method 1 s is approximated byT z 1 This gives usy k y k 1 T u k 1 Letx k y k then we have x k 1 x k T u k clip if necessary y k x k With this method input port 1 does not have direct feedthrough Discrete Time Integrator e Backward Euler method also known as Backward Rectangular or right hand approximation For this method 1 s is approximated by T z z 1 This givesusy k y k 1 T u k Letx k y k 1 then we have x k 1 y k y k x k T x u k clip if necessary With this method input port 1 has direct feedthrough Trapezoidal method For this method 1 s is approximated by T 2 z241 z 1 This givesusy k y k 1 T 2 u k ulk 1 When T is fixed equal to the sampling period let x k
295. nk system bdroot bdroot obj bdroot with no arguments returns the top level system name bdroot obj where obj isa system or block path name returns the name of the top level system containing the specified object name This command returns the name of the top level system that contains the current block bdroot gcb find system gcb 11 7 close_system 11 8 Purpose Syntax Description Examples Close a Simulink system window or a block dialog box close system close system sys close system sys saveflag close system sys newname close system bl k close system with no arguments closes the current system or subsystem window If the current system is the top level system and it has been modified thencl ose system asks if the changed system should be saved to a file before removing the system from memory The current system is defined in the description of the gcs command on page 11 16 close system sys Closes the specified system or subsystem window close system sys saveflag closes the specified top level system window and removes it from memory e Ifsaveflag is 0 the system is not saved e Ifsaveflag is 1 the system is saved with its current name close system sys newname saves the specified top level system toa file with the specified new name then closes the system close system bl k where bl k isa full block path name closes the dialog box ass
296. nresolved Simulink issues an error message and displays these blocks using red dashed lines The error message is Failed to find block source block name in library source library name referenced by block reference block path The unresolved reference block is displayed like this colored red gt Bad Link f Reference Block Name Libraries To fix a bad link you must either e Delete the unlinked reference block and copy the library block back into your model or e Add the directory that contains the required library tothe MATLAB path and select Update Diagram from the Edit menu or e Double click on the reference block On the dialog box that appears correct the pathname and click on Apply or Close All blocks havea Li nkStatus parameter that indicates whether the block isa reference block The parameter can have these values e none indicates that the block is not a reference block e resolved indicates that the block is a reference block and that the link is resolved e unresolved indicates that the block is a reference block but that the link is unresolved Updating a Linked Block Simulink updates reference blocks in a model or library at these times e When the model or library is loaded e When you select Update Diagram from the Edit menu or run the simulation in these circumstances When the library containing the library blocks is unlocked When the model contains a refere
297. ns Set the Initial condition source parameter value to internal If checked limits the states to a value between the Lower saturation limit and Upper saturation limit parameters The upper limit for the integral The default is inf The lower limit for the integral The default is inf If checked adds a saturation output port to the block If checked adds an output port to the block for the block s state The time interval between samples The default is 1 Yes of the reset and external initial condition source on Of parameters Inherited from driving block and parameter Yes One for detecting reset one each to detect upper and lower saturation limits one when leaving saturation Discrete Transfer Fcn Purpose Library Description z 0 5 Implement a discrete transfer function Discrete The Discrete Transfer F cn block implements the z transform transfer function described by the following equations n n 1 n m oe num z _ Numgz numjz NUMpZ den z n n dengz den z den where m 1 and n 1 are the number of numerator and denominator coefficients respectively num and den contain the coefficients of the numerator and denominator in descending powers of z num can bea vector or matrix den must be a vector and both are specified as parameters on the block dialog box The order of the denominator must be greater than or equal to the order of the numerator Block input is s
298. ns in Chapter 9 indicate whether Simulink applies scalar expansion to a block s inputs and parameters Scalar Expansion of Inputs When using blocks with more than one input port such as the Sum or Relational Operator block you can mix vector and scalar inputs When you do this the scalar inputs are expanded into vectors of identical elements whose widths are equal to the width of the vector inputs If more than one block input is a vector they must have the same number of elements This model adds scalar and vector inputs The input from block Constant is scalar expanded to match the size of the vector input from the Constant block The input is expanded to the vector 3 3 3 3 11 3 Creating a M odel 3 12 Scalar Expansion of Parameters You can specify the parameters for vectorized blocks as either vectors or scalars When you specify vector parameters each parameter element is associated with the corresponding element in the input vector s When you specify scalar parameters Simulink applies scalar expansion to convert them automatically into appropriately sized vectors This example shows that a scalar parameter the Gain is expanded toa vector of identically valued elements to match the size of the block input a three element vector Do Constant i an Gain Scope Using Drop Shadows You can add a drop shadow toa block by selecting the block then choosing Show Drop Shadow from the Format menu When you s
299. ntenance e A menu driven graphical user interface makes it easy to use The RTW Ada Extension provides turnkey solutions for the following Ada 83 compilers e Rational VADS for UNIX platforms e Thomson ActivAda for Windows Professional Edition e Thomson ActivAda for Windows NT 1 13 1 G etting Started Blocksets Similar to MATLAB and its application toolboxes The MathWorks offers Blocksets for use with Simulink Blocksets are collections of Simulink blocks that are grouped in a separate library from the main Simulink library The DSP Blockset The DSP Blockset extends Simulink for usein the rapid design and simulation of DSP based devices and systems With the DSP Blockset Simulink provides an intuitive tool for interactive block diagram simulation and evaluation of signal processing algorithms Its graphical programming environment makes it easier for engineers to create modify and prototype DSP designs Simulink is required Applications for the DSP Blockset include design and analysis of communications systems computer peripherals speech and audio processing automotive and aerospace controls and medical electronics It is ideal for both time and frequency domain algorithms including problems such as adaptive noise cancellation The Fixed Point Blockset The Fixed Point Blockset for use with Simulink includes a collection of block diagram components that extend the standard Simulink block library With this new s
300. ntosh select the block name and replace the text e Toinsert characters click between two characters to position the insertion point then insert text e To replace characters drag the mouse to select a range of text to replace then enter the new text When you click the pointer someplace else in the model or take any other action the name is accepted or rejected If you try tochangethename of a block 3 Creating a M odel 3 10 to a name that already exists or to a name with no characters Simulink displays an error message You can modify the font used in a block name by selecting the block then choosing the Font menu item from the Format menu Select a font from the Set Font dialog box This procedure also changes the font of text on the block icon You can cancel edits to a block name by choosing Undo from the Edit menu NOTE If you change the name of a library block all links to that block will become unresolved Changing the Location of a Block Name You can change the location of the name of a selected block in two ways e By dragging the block name to the opposite side of the block or e By choosing the Flip Name command from the Format menu This command changes the location of the block name to the opposite side of the block For more information about block orientation see Changing the Orientation of Blocks on page 3 8 Changing Whether a Block Name Appears To change whether the name of a sel
301. nts a counter The Sum and Unit Delay blocks are selected within a bounding box F4 Sum Unit Delay To Workspace simout Constant i When you release the mouse button the two blocks and all the connecting lines are selected 2 Choose Create Subsystem from the Edit menu Simulink replaces the selected blocks with a Subsystem block This figure shows the model after Creating Subsystems choosing the Create Subsystem command and resizing the Subsystem block so the port labels are readable Constant To Workspace Subsystem If you open the Subsystem block Simulink displays the underlying system as shown below Notice that Simulink adds Inport and Outport blocks to represent input from and output to blocks outside the subsystem Ind t z 1 Sum Unit Delay 99 As with all blocks you can change the name of the Subsystem block Also you can customize the icon and dialog box for the block using the masking feature described in Chapter 6 Labeling Subsystem Ports Simulink labels ports on a Subsystem block The labels arethe names of I nport and Outport blocks that connect the subsystem to blocks outside the subsystem through these ports You can hide the port labels by selecting the Subsystem block then choosing Hide Port Labels from the Format menu You can also hide one or more port labels by selecting the appropriate Inport or Outport block in the subsystem and choosing Hide Name from the Format menu
302. nu commands while they develop and refine their models then enter commands in the MATLAB command window to run the simulation in batch mode Using Menu Commands Running a simulation using menu commands is easy and interactive These commands let you select an ODE solver and define simulation parameters without having to remember command syntax An important advantage is that you can perform certain operations interactively while a simulation is running e You can modify many simulation parameters including the stop time the solver and the maximum step size You can change the solver You can simulate another system at the same time You can click on a line to see the signal carried on that line on a floating unconnected Scope or Display block You can modify the parameters of a block as long as you do not causea change in Thenumber of states inputs or outputs Thesample time The number of zero crossings The vector length of any block parameters Thelength of the internal block work vectors You cannot make changes to the structure of the model such as adding or deleting lines or blocks during a simulation If you need to make these kinds of changes you need to stop the simulation make the change then start the simulation again to see the results of the change Introduction Running a Simulation from the Command Line Running a simulation from the command line has these advantages over running
303. o the trade offs between controller complexity hence the ability to implement it and specifications The Robust Control Toolbox The Robust Control Toolbox provides a specialized set of tools for the analysis and synthesis of control systems that are robust with respect to uncertainties that can arise in the real world The Robust Control Toolbox was created by controls theorists Richard Y Chiang and Michael G Safonov Professional Application Toolboxes The Signal Processing Toolbox The Signal Processing Toolbox contains tools for signal processing Applications include audio e g compact disc and digital audio tape video digital HDTV image processing and compression telecommunications fax and voice telephone medicine CAT scan magnetic resonance imaging geophysics and econometrics The Spline Toolbox The Spline Toolbox by Carl de Boor a pioneer in the field of splines provides a set of M files for constructing and using splines which are piecewise polynomial approximations Splines are useful because they can approximate other functions without the unwelcome side effects that result from other kinds of approximations such as piecewise linear curves The Statistics Toolbox The Statistics Toolbox provides a set of M files for statistical data analysis modeling and Monte Carlo simulation with GUI based tools for exploring fundamental concepts in statistics and probability The Symbolic Math Toolbox The Sy
304. ociated with the specified block or calls the block s CI oseFcn callback parameter if oneis defined Any additional arguments are ignored This command closes the current system close system This command closes thevdp system close system vdp This command saves the engi ne system with its current name then closes it close system engine 1 close_system This command closes the my md 12 system with the namet est sys then closes it close system mymd 12 testsys This command closes the dialog box of the Unit Delay block in the Combustion subsystem of the engi ne system close system engine Combustion Unit Delay See Also bdclose gcs new_system open_system Save system 11 9 delete_block Purpose Syntax Description Example See Also 11 10 Delete a block from a Simulink system delete block blk delete block blk where bik isa full block path name deletes the specified block from a system This command removes block Out1 from thevdp system delete block vdp Out 1 add_block delete_line Purpose Syntax Description Example See Also Delete a line from a Simulink system delete line sys oport iport delete _line sys oport iport deletes the line extending from the specified block output port oport tothe specified block input port iport oport and iport are strings consisting of a block name and a port identi
305. ocks with differing word lengths may be used in the same block diagram Scaling of fixed point values is achieved by specifying the location of the binary point within the fixed point blocks During simulation data types can be changed allowing you to immediately see the effects of different word sizes binary point locations rounding versus truncation and overflow checking Another powerful feature of this blockset is automatic location of the binary point to give maximum precision without overflow By using the data range blocks you can fix binary point locations to appropriate values The Fixed Point Blockset requires Simulink 1 3 and MATLAB 4 2c and is currently shipping on PC and Macintosh The Nonlinear Control Design Blockset The Nonlinear Control Design NCD Blockset offers time domain based robust nonlinear control design Controller designs are developed as block diagrams in Simulink You select a set of tunable model parameters and 1 15 1 G etting Started graphically place time response constraints on selected output signals Successive simulation and optimization methods are applied automatically thereby tuning the selected model parameters Simulink is required with the NCD Blockset 1 16 Quick Start Running a Demo Model Description oftheDemo Some Things toTry What This Demo Illustrates Other Useful Demos Building a Simple Model 2 2 2 3 2 4 2 5 2 Q uick Start
306. oduce only scalar output i Trigonometric Function Trigonometry Trigonometric and hyperbolic functions Parameters The trigonometric function Function Apply Revert Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion Of the input when the function requires two inputs Vectorized Yes Zero Crossing No 9 157 Uniform Random Number Purpose Library Description wh Parameters and Dialog Box Characteristics 9 158 Generate uniformly distributed random numbers Sources The Uniform Random Number block generates uniformly distributed random numbers over a specifiableinterval with a specifiable starting seed The seed is reset each timea simulation starts The generated sequence is repeatable and can be produced by any Uniform Random Number block with the same seed and parameters To generate a vector of random numbers specify the Initial seed parameter as a vector To generate normally distributed random numbers use the Random Number block described on page 9 111 Avoid integrating a random signal because solvers are meant to integrate relatively smooth signals Instead use the Band Limited White Noise block i Uniform Random Number r Uniform Random Number Outputs a uniformly distributed random signal Output is repeatable for a given seed p Parameters The minimum of the interval The default is 1 Minimum i The maxim
307. of n elements describes a polynomial of degree n 1 The block icon displays the numerator and denominator according to how they are specified For a discussion of how Simulink displays the icon see the Transfer Fcn block description on page 9 151 Discrete Filter r Discrete Filter Vector expression for numerator and denominator Coefficients are for ascending powers of 1 z The vector of numerator coefficients The default is 1 Parameters Numerator m Denominator 12 Sample time 1 Apply Revert Help The vector of denominator coefficients The default is 1 2 The time interval between samples 9 37 Discrete Filter Characteristics Direct Feedthrough Only ifthelengths of the Numerator and Denominator parameters are equal Sample Time Discrete Scalar Expansion No States Length of Denominator parameter 1 Vectorized No Zero Crossing No 9 38 Discrete Pulse Generator Purpose Library Description An Parameters and Dialog Box Characteristics Generate pulses at regular intervals Sources The Discrete Pulse Generator block generates a series of pulses at regular intervals The pulse width is the number of sample periods the pulse is high The period is the number of sample periods the pulse is high and low The phase delay is the number of sample periods before the pulse starts The phase delay can be positive or negative but must not be larger th
308. of the number of inputs to the S function W riting S Functions as C M EX iles Macros Used with Work Vectors Simulink provides macros for allocating the work vector elements assigning variables to the elements and accessing these variables e Indudeinthemal InitializeSizes function macros that define the number of work vector elements ssSetNumRWork S numRWork defines the number of real work vector elements ssSetNuml Work S numl Work defines the number of integer work vector elements ssSetNumPWork S numPWork defines the number of pointer work vector elements Includein themd InitializeConditions function macros that set the work vector element values ssSetRWorkVal ue S rworkl dx rworkVal ue defines the value of real work vector element rworkl dx toberworkValue ssSetlWorkValue iworkldx iworkValue defines the value of integer work vector element i work dx to bei workValue ssSetPWorkValue S pworkl dx pworkVal ue defines the value of pointer work vector element pworkil dx tobepworkValue e These macros get the work vector element values ssGetRWorkVal ue S rworkl dx obtains the value of real work vector element rworkl dx ssGet WorkValue S iworkl dx obtains the value of integer work vector element i workl dx ssGetPWorkValue S pworkl dx obtains the value of pointer work vector element pworki dx You specify the number of work vector elements your block uses in the mdlInitializeSizes f
309. of these t Final to specify the stop time The start time is 0 tStart tFinal tospecify the start and stop times tStart OutputTimes tFinal tospecify the start and stop times and time points to be returned int Generally t will include more time points Out put Ti mes is equivalent to choosing Produce additional output on the dialog box 4 22 sim Examples See Also options Optional simulation parameters specified as a structure created by thesi mset command See page 4 24 ut Optional external inputs to top level Inport blocks ut can be either one or more MATLAB commands expressed as a string or a matrix of values If a string containing a function u t MATLAB evaluates the function at each time step If a matrix specified asut t ul u2 where t t1 tn the first column must be a vector of times in ascending order The remaining columns are the corresponding values for the inputs Simulink linearly interpolates between values when necessary pl pn Additional S function parameters specified as though this call were used sys sfun t x u flag pl p2 pn S function parameters are used only in M file and ME X file systems This command simulates the vdp model using all default parameters t x yl sim vdp This command simulates thevdp model using the parameter values associated with the model but defines a value for the Ref i ne parameter t x y sim vdp simset Refine 2
310. of vari abl ename NOTE While these commands are identical in name to their corresponding MATLAB functions they provide only the functionality described above To display more than one line of text use n toindicate a line break For example the figure below shows two samples of thedi sp command disp Sample Mask disp Sampleinttaste Sample le Mask ample Ma Mask Displaying Graphics on the Block Icon You can display plots on your masked block icon by entering one or more p ot commands Y ou can use these forms of the plot command plot Y plot X1 Y1 X2 Y2 plot Y plots for a vector Y each element against its index If Y is a matrix it plots each column of the matrix as though it were a vector plot X1 Y1 X2 Y2 plots the vectors Y1 against X1 Y2 against X2 and so on Vector pairs must be the same length and the list must consist of an even number of vectors The Icon Page For example this command generates the plot that appears on the icon for the Ramp block in the Sources library The icon appears below the command plot 0 1 5 0 0 4 b Ramp Plot commands can include NaN andi nf values When NaNsorinfsare encountered Simulink stops drawing then begins redrawing at the next numbers that are not NaN orinf The appearance of the plot on the icon depends on the value of the Drawing coordinates parameter For more information see Controlling Icon Properties on page
311. olbox The Financial Toolbox operates with MATLAB to provide a robust set of financial functions essential to financial and quantitative analysis Applications include pricing securities calculating interest and yield analyzing derivatives and optimizing portfolios The Financial Toolbox requires the Statistics and Optimization Toolboxes The Simulink graphical interface is recommended for Monte Carlo and non stochastic simulations for pricing fixed income securities derivatives and other instruments The Financial Toolbox includes functions for the input processing and output of financial data e Fixed income pricing yield and sensitivity routines e Cash flow evaluation and financial accounting functions e Derivatives analysis procedures e Portfolio analysis tools e Date functions e Graphic formats and cash formatting functions The Frequency Domain System Identification Toolbox The Frequency Domain System Identification Toolbox by Istvan Kollar in cooperation with J ohan Schoukens and researchers at the Vrije Universiteit in Brussels is a set of M files for modeling linear systems based on measurements of the system s frequency response The Fuzzy Logic Toolbox The Fuzzy Logic Toolbox provides a complete set of GUI based tools for designing simulating and analyzing fuzzy inference systems Fuzzy logic provides an easily understandable yet powerful way to map an input space to an output space with arbitrary complexity with r
312. on Once the data is in the state space form or converted toan LTI object you can apply functions in the Control System Toolbox for further analysis e Conversion to an LTI object sys ss A B C D e Bode phase and magnitude frequency plot bode A B C D orbode sys e Linearized time response step A B C D or step sys impulse A B C D or i mpulse sys Isim A B C D u t or Isim sys u t Other functions in the Control System Toolbox and Robust Control Toolbox can be used for linear control system design When the model is nonlinear an operating point may be chosen at which to extract the linearized model The nonlinear model is also sensitive to the perturbation sizes at which the model is extracted These must be selected to balance the trade off between truncation and roundoff error Extra arguments tol i nmod specify the operating point and perturbation points A B C D linmod sys x u pert xpert upert For discrete systems or mixed continuous and discrete systems use the function di i nmod for linearization This has the same calling syntax as i nmod except that the second right hand argument must contain a sample time at which to perform the linearization F or more information see the description of the i nmod command on page 5 9 Using i nmod tolinearizea model that contains Derivative or Transport Delay blocks can be troublesome Before linearizing replace these blocks with specially designed blocks t
313. on e Control framework API uses customizable makefiles to build and download object files to target hardware automatically The Simulink Real Time W orkshop Portable code facilitates usage in a wide variety of environments e Concise readable and well documented code provides ease of maintenance e Interactive parameter downloading from Simulink to external hardware allows system tuning on the fly e A menu driven graphical user interface makes the software easy to use The Real Time Workshop supports the following target environments e dSPACE DS1102 DS1002 DS1003 using TI C30 C31 C40 DSPs e VxWorks VME 68040 e 486 PC based systems with Xycom Matrix Data Translation or Computer Boards I O devices and Quanser M ultiq board 1 11 1 G etting Started 1 12 The Real Time Workshop Ada Extension The Simulink Real Time Workshop RTW Ada Extension automatically generates Ada code directly from Simulink block diagrams This allows the execution of continuous discrete time and hybrid system models on a wide range of computer platforms including real time hardware Simulink is required RTW Ada Extension can be used for Rapid Prototyping As a rapid prototyping tool the RTW Ada Extension enables you to implement your designs quickly without lengthy hand coding and debugging Control and dynamic system algorithms can be implemented by developing graphical Simulink block diagrams and automatically generating Ada
314. onally executed subsystem F or more information about conditionally executed subsystems see Chapter 7 The visibility of a Goto block tag determines the From blocks that can receive its signal For more information see the descriptions of the Goto block on page 9 71 and the Goto Tag Visibility block on page 9 73 The block icon indicates the visibility of the Goto block tag e A local tag name is enclosed in square brackets e A scoped tag name is enclosed in braces e A global tag name appears without additional characters From Parameters and Dialog Box Characteristics gt From Receives signals from the Goto block with the specified tag If the tag is defined as scoped in the Goto block then a Goto Tag Visibility block must be used to define the visibility of the tag After Update Diagram the block icon displays the selected tag name local tags are enclosed in brackets and scoped tag names are enclosed in braces Parameters Goto tag A Apply Revert Help Sample Time The tag of the Goto block passing the signal to this From block Inherited from block driving the Goto block Vectorized Yes 9 65 From File 9 66 Purpose Library Description untitled mat fy Read data from a file Sources The From File block outputs data read from the specified file The block icon displays the name of the file supplying the data The fi
315. onnects a linetotheinput port of another block This line called a branch line connects the Sine Wave output to the Integrator block and carries the same signal that passes from the Sine Wave block to the Mux block Drawinga branch lineis slightly different from drawing theline you just drew To weld a connection to an existing line follow these steps 1 First position the pointer on theline between the Sine Wave and the Mux block A LO V le Mux b Sine Wave 1 Mux Pi Scope Integrator 2 Press and hold down the Ctrl key on a Windows or X Windows system or the Option key on a Macintosh Press the mouse button then dragthe pointer tothe Integrator block s input port or over theIntegrator block itself Sine Wave L 4 Mux s Scope Integrator 3 Releasethe mouse button Simulink draws a line between the starting point and the Integrator block s input port Sine Wave 1 Mux s Scope Integrator Finish making block connections When you re done your model should look something like this 7 Mux Sine Wave 1 Mux s Scope Integrator 2 11 2 Q uick Start 2 12 Now open the Scope block to view the simulation output K eeping the Scope window open run the simulation for 10 seconds First set the simulation parameters by choosing Parameters from the Simulation menu On the dialog box that appears not
316. ons When the S function is within an enabled subsystem themd ni tial izeConditions iscalled each timethat the subsystem becomes enabled 8 47 8 S Functions The initial conditions vector is represented by this diagram which shows the order in which the states are defined and indicates the macros used to define the number of states x0 Continuous states ssSetNumContStates Discrete ssSetNumDiscStates states Example Defining a Vector of Initial Conditions This example shows how to define a vector of initial conditions The following code initializes the continuous states to 1 0 x Set initial conditions static void mdllnitializeConditions double x0 SimStruct S int i nCStates nCStates for i 0 ssGetNumCont States S on x0 1 0 lt nCStates i Allocating Work Vectors and Setting Their Values If your S function needs persistent memory storage use S function work vectors instead of static or global variables If you use static or global variables they are used by multiple instances of your S function The ability to keep track of multiple instances of an S function is called reentrancy You can create an S function that is reentrant by using work vectors These are persistent storage locations that Simulink manages for an S function Integer floating point and pointer data types are supported The number of elements in each vector can be specified dynamically as a function
317. ork S i Work i 3 8 57 madllnitializeSampleTimes 8 58 Purpose Declaration Arguments Description Initialize sample times array static void mdllnitializeSampleTimes SimStruct S SimStruct 5 Thesimstruct for this block The md nitializeSampleTi mes function initializes the sample times and offsets arrays stored in thesi mSt ruct Simulink uses these arrays to compute when the next sample hit will occur so the solver stops at that time The sample times and offsets are set using the following macros ssSetSampleTimeEvent S st_index sample _ti me ssSetOffsetTimeEvent S st_index offset _ti me where the arguments are as follows 5 Thesi mStruct st_index When setting asampletime st_index isthearray element of the sample time To set one sample time specify anst_index value of 0 to set two sample times invoke the macro twice with st_index values of 0 and 1 and soon When setting an offset st_ index corresponds to the index of the sample time to which the offset applies sample_time Thesampletimefor thest_index element offset_time The offset for thest index element If the S function is purely continuous in nature you should set thefirst sample time and offset to zero The number of sample times set in this function must match the number of sample times set by thess Set NumSamp eTi mes macroin the mdlInitializesizes function For more information about setting sample times and offset
318. ort check box Selecting this option allows the system to determine what caused thetrigger Thewidth ofthesignal isthe width ofthetriggering signal Thesignal valueis e 1 for a signal that causes a rising trigger e 1 for a signal that causes a falling trigger e 0 otherwise 9 155 Trigger 9 156 Parameters and Dialog Box Characteristics Trigger Trigger Port Place this block in a subsystem to create a triggered subsystem The type of event that triggers execution of the r Parameters su bsystem Trigger type rising T Show output port Apply Revert Help If checked Simulink draws the Trigger block output port and outputs the trigger signal Sample Time Determined by the signal at the trigger port Vectori zed Yes Trigonometric Function Purpose Library Description Parameters and Dialog Box Characteristics Perform a trigonometric function Nonlinear The Trigonometric Function block performs numerous common trigonometric functions You can select one of these functions from the Function list sin cos tan asin acos atan atan2 sinh cosh andt anh The block output is the result of the function operating on the input or inputs The name of the function appears on the block icon Simulink automatically draws the appropriate number of input ports Use the Trigonometric Function block instead of the Fcn block when you want vectorized output because the Fcn block can pr
319. os asz er os Poles as poles and Gain as gai n theicon looks like this gain zeros s gt poless 9 165 Zero Pole Parameters and Dialo g Matrix expression for zeros Vector expression for poles Box and gain Output width equals the number of columns in zeros matrix or one if zeros is a vector Zero Pole r Zero Pole Parameters Zeros m The matrix of zeros The default is 1 Poles 0 1 The vector of poles The default is 0 1 Gain 1 Apply Revert Help Characteristics Direct Feedthrough Only if the lengths of the Poles and Zeros parameters are equal The vector of gains The default is 1 Sample Time Continuous Scalar Expansion No States Length of Poles vector Vectorized No Zero Crossing No 9 166 Zero Pole 9 167 Zero Pole 9 168 Zero Pole 9 169 Zero Pole 9 170 Zero Pole 9 171 Zero Pole 9 172 Zero Pole 9 173 Zero Pole 9 174 Zero Pole 9 175 Zero Pole 9 176 Additional Topics How Simulink Works Zero Crossings Algebraic Loops Invariant Constants Discrete Time Systems Discrete Blocks Sample Time Purely Discrete Systems Multirate Systems Sample Time Colors y Mixed Continuous and Discrete Systems 10 Additional Topics How Simulink Works 10 2 Each block within a Simulink model has these general characteristics a vector of inputs u a v
320. ot be computed without knowing the values of the signals entering the blocks at these input ports Some examples of blocks with direct feedthrough inputs are e The Elementary Math block e The Gain block e The Integrator block s reset and initial condition ports e The Product block e The State Space block when there is a nonzero D matrix e The Sum block e The Transfer Fcn block when the numerator and denominator are of the same order e The Zero Pole block when there are as many zeros as poles To determine whether a block has direct feedthrough consult the Characteristics table that describes the block in Chapter 9 An algebraic loop occurs when an input port with direct feedthrough is driven by the output of the same block either directly or by a feedback path through other blocks with direct feedthrough An example is this simple scalar loop Mathematically this loop implies that the output of the Sum block is an algebraic state z constrained to equal the first input u minus z i e Z u Z The solution of this simple loop is z u 2 but most algebraic loops cannot be 10 7 10 Additional Topics 10 8 solved by inspection It is easy to create vector algebraic loops with multiple algebraic state variables z1 z2 etc as shown in this model Solve f z 0 te The Algebraic Constraint block in the Nonlinear library described on page 9 10 is a convenient way to model algebraic equations and specify
321. ou how to build a model using many of the model building commands and actions you will use to build your own models The instructions for building this model in this section are brief All of the tasks are described in more detail in the next chapter The model integrates a sine wave and displays the result along with the sine wave The block diagram of the model looks like this Mux Sine Wave 1 Ber Mux s Scope Integrator Typesi mul i nk in the MATLAB command window to display the Simulink block library and if no other model window is open a new untitled model window The Simulink block library window looks like this Library simulink L lolx Eile Edit Simulation Format Tools sial ww ns RAE Sources Sinks Discrete Linear Nonlinear Connections Blocksets amp Simulink Block Library Toolboxes Copyright Cc 1990 97 by The MathWorks Inc You might want to move the new model window tothe right side of your screen so you can see its contents and the contents of block libraries at the same time In this model you get blocks from these libraries e Sources library the Sine Wave block e Sinks library the Scope block e Linear library the Integrator block e Connections library the Mux block Open the Sources library to access the Sine Wave block To open a block library double click on the library s icon Simulink displays a window that contains all
322. ou seethe outline of the block and its name move with the pointer ES untitled iol x File Edit Simulation Format 2 8 Building a Simple M odel When the pointer is where you want the block to be in the model window release the mouse button A copy of the Sine Wave block is now in your model window untitled oj x File Edit Simulation Format Sine Wave In the same way copy the rest of the blocks into the model window You can move a block from one place in the model window to another using the same dragging technique you used to copy the block You can move a block a small amount by selecting the block then pressing the arrow keys With all the blocks copied into the model window the model should look something like this g Sine Wave Mux Scope 5 Integrator If you examine the block icons you seean angle bracket on theright of the Sine Wave block and three on the left of the Mux block The gt symbol pointing out of a block is an output port if the symbol points to a block it is an input port A signal travels out of an output port and into an input port of another block through a connecting line When the blocks are connected the port symbols disappear Input port lt _ Output port 5 Integrator You might have noticed that the Mux block has three input ports but only two input signals Tochangethenumber of input ports open the M ux block s dialog box by double c
323. our S function needs to have its md Update routine called and it does not satisfy either of the above conditions you must specify that it has a discrete state using thessSet NumDi scStates macrointhemdl nitializeSizes function The inputs to this function are the current states the current inputs the Si mStruct and a task ID Thetask ID is used when the system is executing in a multithreaded environment mdlUpdate Example static void mdl Update double x double u SimStruct 5 nt tid x Compute the discrete states as just the sampled continuous states The use of sslsSampl eHitEvent ensures that the discrete states should only be x updated on discrete time hits if sslsSampleHitEvent S 0 tid int i for i 0 i lt ssGetNumDiscStates S i x ssGetNumContStates S i x i 8 65 mdlUpdate Block Reference What Each Block Reference Page Contains 9 2 The Simulink Block Libraries 9 3 9 Block Reference 9 2 What Each Block Reference Page Contains Blocks appear in alphabetical order and contain this information The block name icon and block library that contains the block The purpose of the block A description of the block s use The block dialog box and parameters The block characteristics including some or all of these as they apply to the block Direct Feedthrough whether the block or any of its ports has direct feedt
324. ovariance of the signal from the Band Limited White Noise block is not the same as the Noise power intensity dialog box parameter This parameter is actually the height of the PSD of the white noise While the covariance of true white noise is infinite the approximation used in this block has the property that the covariance of the block output is the Noise Power divided by te Band Limited White Noise Parameters Band Limited White Noise a nd Di a log r Continuous White Noise mask White noise for continuous s domain systems Box Band limited using zero order hold Parameters The height of the PSD ofthe white noise The Noise power default value is 0 1 0 1 Sample time The correlation time of the noise The default 01 valueis 0 1 Seed 23341 The starting seed for the random number generator The default value is 23341 Apply Revert Help Characteristics Sample Time Discrete Scalar Expansion Of Noise power and Seed parameters and output Vectorized Yes Zero Crossing No 9 17 Chirp Signal 9 18 Purpose Library Description Nip Parameters and Dialog Box Characteristics Generate a sine wave with increasing frequency Sources The Chirp Signal block generates a sine wave whose frequency increases at a linear rate with time You can use this block for spectral analysis of nonlinear systems The block generates a scalar or vector output Chirp Signal chirp mask
325. pansion Yes Vectorized Yes Zero Crossing No 9 107 Pulse Generator Purpose Generate pulses at regular intervals Library Sources Description The Pulse Generator block generates a series of pulses at regular intervals Use the Pulse Generator block for continuous systems To generate discrete au signals use the Discrete Pulse Generator block described on page 9 39 Pa ra meters Pulse Generator a nd Di a log r Pulse Generator mask Pulse Generator ee Box The pulse period in seconds The default is one m Parameters i second Period secs 1 cea ee The duty cycle the percentage of the pulse period a that the signal is on The default is 50 percent Amplitude x 1 The pulse amplitude The default is 1 Start time gt m ene The delay before the pulse is generated in l seconds The default is 0 seconds Apply Revert Help Characteristics SampleTime Inherited Scalar Expansion Of parameters Vectori zed Yes Zero Crossing No 9 108 Quantizer Purpose Library Description al Parameters and Dialog Box Characteristics Discretize input at a specified interval Nonlinear The Quantizer block passes its input signal through a stair step function so that many neighboring points on theinput axis are mapped to one point on the output axis The effect is to quantize a smooth signal into a stair step output The output is computed using the round to nearest method which produces a
326. parameter values for blocks within the masked system You create the mask interface by defining prompts for parameter values on the Initialization page The Initialization page for the mx b sample masked system looks like this EJ Mask Editor samplemask mx b BBE Icon Initialization Documentation Mask type SampleMaskedBlock Prompt Type Variable List of prompts Intercept lt lt end of parameter list gt gt Add Delete Down Prompt Slope Control type Edit Variable m Assignment Evaluate Initialization commands Full description of each parameter prompt ri E J Initialization commands Apply Revert Unmask Help Close Prompts and Associated Variables A prompt provides information that helps the user enter or select a value for a block parameter Prompts appear on the mask dialog box in the order they appear in the Prompt list When you define a prompt you also specify the variable that is to store the parameter value choose the style of control for the prompt and indicate how the value is to be stored in the variable If the Assignment type is Evaluate the value entered by the user is evaluated by MATLAB before it is assigned to the variable If the type is Literal the value entered by the user is not evaluated but is assigned tothe variable as a string The Initialization Page For example if the user enters the string gai n in an edit field and
327. put Options The Output options area of the dialog box enables you to control how much output the simulation generates You can choose from three popup options e Refine output e Produce additional output e Produce specified output only Refine Factor The Refine output choice provides additional output points when the simulation output is too coarse This parameter provides an integer number of output points between time steps for example a refine factor of 2 provides output midway between the time steps as well as at the steps The default refine factor is 1 To get smoother output it is much faster to change the refine factor instead of reducing the step size When the refine factor is changed the solvers generate additional points by evaluating a continuous extension formula at those points Changing the refine factor does not change the steps used by the solver Therefine factor applies to variable step solvers and is most useful when using ode45 Theode45 solver is capable of taking large steps when graphing simulation output you may find that output from this solver is not sufficiently smooth If this is the case run the simulation again with a larger refine factor A value of 4 should provide much smoother results Produce Additional Output The Produce additional output choice enables you to specify directly those additional times at which the solver generates output Similar to the refine factor selecting this option does not c
328. put port The block output is the product of all inputs marked divided by all inputs marked For example this block icon is the result of entering as the parameter value E If the valueis a scalar greater than 1 the block multiplies all inputs If any input is a vector the block output is an element by element product across the inputs If all inputs are scalars the output is a scalar For a block having n inputs if any input is a vector each element of the output is generated as y ulxu2 x xun Ifthevalueis 1 the block output is the scalar product of the elements of the input vector y Hu This model represents using the Product block in this way The solid line input signal indicates that theinput is a vector If necessary Simulink resizes the block to show all input ports If the number of inputs is changed ports are added or deleted from the bottom of the block 9 106 Product Parameters Bull Product a nd Dia log Multiply or divide inputs Specify one of the following Box a or for each input port e g b scalar greater than 1 multiplies all input ports c 1 multiplies all elements of single input vector Parameters Number of inputs 2 Apply Revert Help Characteristics Direct Feedthrough Yes Either the number of inputs to the block or a combination of and symbols The default is 2 Sample Time Inherited from driving block Scalar Ex
329. r Below is the M file code for thet i mest wo m block function sys x0 str ts timestwo t x u flag Dispatch the flag The switch function controls the calls to S function routines at each simulation stage switch flag case 0 sys x0 str ts mdll nitializeSizes Initialization case 3 sys mdl Outputs t x u Calculate outputs case 1 2 4 9 sys Unused flags otherwise error Unhandled flag numdstr flag Error handling End of function ti mest wo W riting S Functions as M Files The first four input arguments which Simulink passes to the S function must be the variablest x u andf ag t the time x the state vector required even if as in this case there are no states u the input vector e flag the parameter that controls the S function subroutine calls at each simulation stage Simulink also requires that the output parameters sys x0 str andts be placed in the order given These parameters are sys a generic return argument The values returned depend on the flag value For example forflag 3 sys contains the S function outputs x0 the initial state values an empty vector if there are no states in the system str provided only for consistency with the S function API for block diagrams For M file S functions set it toan empty matrix ts atwocolumn matrix containing the sample times and offsets of states associated with the block Sample times should be dec
330. r You can create a subsystem in two ways e Add a Subsystem block to your model then open that block and add the blocks it contains to the subsystem window e Add the blocks that make up the subsystem then group those blocks into a subsystem 3 27 3 Creating a M odel 3 28 Creating a Subsystem by Adding the Subsystem Block Tocreate a subsystem before adding the blocks it contains add a Subsystem block to the model then add the blocks that make up the subsystem 1 Copy the Subsystem block from the Connections library into your model 2 Open the Subsystem block by double clicking on it 3 In the empty Subsystem window create the subsystem U se Inport blocks to represent input from outside the subsystem and Outport blocks to represent external output For example the subsystem below includes a Sum block and Inport and Outport blocks to represent input to and output from the subsystem Creating a Subsystem by Grouping Existing Blocks If your model already contains the blocks you want to convert to a subsystem you can create the subsystem by grouping those blocks 1 Enclose the blocks and connecting lines you want to include in the subsystem within a bounding box You cannot specify the blocks to be grouped by selecting them individually or by using the Select All command For more information see Selecting Multiple Objects Using a Bounding Box on page 3 5 For example this figure shows a model that represe
331. r e f the Number of outputs vector elements are all 1 the number of outputs is equal to the number of vector elements and the widths are dynamically sized Specifying the parameter in this way is the same as specifying the parameter as a scalar whose value is the number of elements For example entering 1 1 1 isthesameas specifying a parameter value of 3 Simulink draws the specified number of output ports on the block resizing the block if necessary When the number of ports is increased or decreased ports are added or removed from the bottom of the block icon Using a Variable to Provide the Number of Outputs Parameter When you specify the Number of outputs parameter as a variable Simulink issues an error message if the variable is undefined in the workspace Demux Splits vector signal into scalars or smaller vectors Parameters Number of outputs 3 Apply Revert Help Thenumber and width of outputs Thetotal of the output widths must match the width of the input line Demux Characteristics SampleTime Inherited from driving block Vectorized Yes 9 33 Derivative Purpose Library Description dufdt I 9 34 Dialog Box Output the time derivative of the input Linear The Derivative block approximates the derivative of its input by computing AU At where Au is the change in input value and At is the change in time since the previous simulation time step The block acc
332. r Expansion N A Vectorized Yes Zero Crossing No Math Function Purpose Library Description Parameters and Dialog Box Characteristics Perform a mathematical function Nonlinear The Math Function block performs numerous common mathematical functions You can select one of these functions from the Function list exp og 10 logl0 square sgrt pow reciprocal hypot rem andmod The block output is the result of the function operating on the input or inputs The name of the function appears on the block icon Simulink automatically draws the appropriate number of input ports Use the Math Function block instead of the Fcn block when you want vectorized output because the F cn block can produce only scalar output Math Function Math Mathematical functions including logarithmic exponential power and modulus functions Parameters Function The mathematical function Apply Revert Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion Of the input when the function requires two inputs Vectorized Yes Zero Crossing No 9 93 MATLAB Fcn Purpose Library Description WATLAB N Function Parameters and Dialog Box 9 94 Apply a MATLAB function or expression to the input Nonlinear The MATLAB Fcn block applies the specified MATLAB function or expression to the input The block accepts one input and generates one output The specifi
333. r input parameters are used BASE_ADDRESS ARG GAIN RANGE ARG PROG GAIN ARG and NUM OF CHANNELS ARG The code uses def i ne statements to associate particular input arguments with the parameter names Input Arguments define BASE ADDRESS ARG ssGetArg S 0 define GAIN RANGE_ARG ssGetArg S 1 define PROG GAIN ARG ssGetArg S 2 define NUM OF CHANNELS ARG ssGetArg S 3 When running the simulation the user enters four variable names or values in the S Function parameters field of the block s dialog box The first corresponds to the first expected parameter BASE_ADDRESS_ARG The second corresponds to the next expected parameter and so on Themdl nitializeSizes function contains this statement ssSetNumlnputArgs S 4 Simulink always passest x and u into S functions These parameters are not included in S Function parameters Only additional parameters that you want to pass to the S function areincluded here For an example to how to pass additional parameters see dl i mi nt c in thesi mul ink src directory Parameter Changes To notify an S function of parameter changes the S function must register a md CheckParameters routine This routine will be called any time after mdl nitializeSizes has been called W riting S Functions as C M EX iles W hen Simulink Calls the mdlUpdate Function An S function s md Update function is called if and only if the S function has one or more discrete states or does no
334. r limit e If theinput is less than or equal to the lower limit the output is the input minus the lower limit This sample model uses lower and upper limits of 0 5 and 0 5 with a sine wave as input simout Sine Wave Mux To Workspace This plot shows the effect of the Dead Zone block on the sine wave While the input the sine wave is between 0 5 and 0 5 the output is zero 1 9 28 Dead Zone Parameters and Dialog Box Characteristics Dead Zone r Dead Zone Outputs zero for inputs within the deadzone the deadzone Parameters Start of dead zone 0 5 End of dead zone 0 5 Apply Revert Help signals by either the Start or End value when outside of Offsets input The lower limit of the dead zone The default is 0 5 The upper limit of the dead zone The default is 0 5 Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving block Of parameters Yes Yes to detect when the limits are reached 9 29 Demux Purpose Separate a vector signal into output signals Library Connections Description The Demux block separates a vector input signal into output lines each of which can carry a scalar or vector signal Simulink determines the number and i widths of the output signals by the Number of outputs parameter Demus p pemah Scalar Number of Outputs If the Number of outputs parameter is a scal
335. re saving a model whose model file was previously saved use the Save command to replace the file s contents or the Save As command to save the model with a new name or location 3 38 Printing a Block Diagram Printing a Block Diagram You can print a block diagram by selecting Print from the File menu on a Microsoft Windows or Macintosh system or by using theprint command in the MATLAB command window on all platforms On a Microsoft Windows system the Print menu item prints the block diagram in the current window On a Macintosh system the Print menu item prints the system in the active window Print Dialog Box When you select the Print menu item the Print dialog box appears The Print dialog box enables you to selectively print systems within your model Using the dialog box you can e Print the current system only e Print the current system and all systems above it in the model hierarchy e Print the current system and all systems below it in the model hierarchy with the option of looking into the contents of masked and library blocks e Print all systems in the model with the option of looking into the contents of masked and library blocks The portion of the Print dialog box that supports selective printing is similar on supported platforms This figure shows how it looks on a Microsoft Windows system In this figure only the current system is to be printed Options o 2 C Current system Current syst
336. reater than the Upper saturation limit and the input is positive the output is held at the Upper saturation limit To generate a signal that indicates when the state is being limited select the Show saturation port check box A saturation port appears below the block output port as shown on this figure Output 4 Input _ gt Saturation s Integrator The signal has one of three values e 1 indicates that the upper limit is being applied e O indicates that the integral is not limited e l indicates that the lower limit is being applied Integrator When this option is selected the block has three zero crossings one to detect when it enters the upper saturation limit one to detect when it enters the lower saturation limit and one to detect when it leaves saturation Resetting the State The block can reset its state to the specified initial condition based on an external signal To cause the block to reset its state select one of the External reset choices A trigger port appears below the block s input port and indicates the trigger type as shown in this figure Input 1 Output Integrator Select rising to trigger the state reset when the reset signal has a rising edge Select falling to trigger the state reset when the reset signal has a falling edge Select either to trigger the reset when either a rising or falling signal occurs The reset port has direct feedthrough If the block output is fed back into
337. recognition and nonlinear system identification and control The Optimization Toolbox The Optimization Toolbox contains commands for the optimization of general linear and nonlinear functions including those with constraints An optimization problem can be visualized as trying to find the lowest or highest point in a complex highly contoured landscape An optimization algorithm can thus be likened to an explorer wandering through valleys and across plains in search of the topographical extremes The Partial Differential Equation Toolbox The Partial Differential Equation Toolbox extends the MATLAB Technical Computing Environment for the study and solution of PDEs in two space dimensions 2 D and time The PDE Toolbox provides a set of command line functions and an intuitive graphical user interface for preprocessing solving and postprocessing generic 2 D PDEs using the Finite Element Method FEM The toolbox also provides automatic and adaptive meshing capabilities and a suite of eight application modes for common PDE application areas such as heat transfer structural mechanics electrostatics magnetostatics and diffusion These application areas are common in the fields of engineering and physics The QFT Control Design Toolbox The Quantitative F eedback Theory Toolbox by Yossi Chait Craig Borghesani and Oded Y aniv implements QFT a frequency domain approach to controller design for uncertain systems that provides direct insight int
338. red Thei th statex is perturbed tox i xpert i Thej th input u is perturbed tou j upert j i nmod obtains linear models from systems of ordinary differential equations described as Simulink models i nmod returns the linear model in state space form A B C D which describes the linearized input output relationship x Ax Bu y Cx Du Inputs and outputs are denoted in Simulink block diagrams using Inport and Outport blocks A B C D linmod sys obtains the linearized model of s ys around an operating point with the state variables x and the input u set to zero i nmod perturbs the states around the operating point to determine the rate of change in the state derivatives and outputs J acobians This result is used to calculate the state space matrices Each state x i is perturbed to x i A i 5 9 Linearization Analysis 5 10 where Adi 6 1 x i Likewise thej th input is perturbed to uj Aj where AG 6 1 u Discrete Time System Linearization The function dl i nmod can linearize discrete multirate and hybrid continuous and discrete systems at any given sampling time Use the same calling syntax for dl i nmod as for inmod but insert the sample time at which to perform the linearization as the second argument F or example Ad Bd Cd Dd dlinmod sys Ts x u produces a discrete state space model at the sampling timeTs and the operating point given by the state vec
339. replace block sys blk1 blk2 replaces all blocksin sys having the block or mask type bIk with bl k2 1f blk2 isa Simulink built in block only the block name is necessary If b k isin another system its full block path name is required If noprompt is omitted Simulink displays a dialog box that asks you to select matching blocks before making the replacement Specifying the noprompt argument suppresses the dialog box from being displayed If a return variableis specified the paths of the replaced blocks are stored in that variable replace block sys Parameter value bl k replaces all blocks in sys having the specified values for the specified parameters with bl k You can specify any number of parameter value pairs NOTE Because it may be difficult to undo the changes this command makes it is a good idea to save your system first This command replaces all Gain blocks in thef 14 system with Integrator blocks and stores the paths of the replaced blocks in RepNames Simulink lists the matching blocks in a dialog box before making the replacement RepNames replace_block f14 Gain Integrator This command replaces all blocks in the Unlocked subsystem in thec l ut ch system having a Gain of bv with the Integrator block Simulink displays a dialog box listing the matching blocks before making the replacement replace _block clutch Unlocked Gain bv Integrator This co
340. rete systems are composed of both sampled and continuous blocks Such systems can be simulated using any oftheintegration methods although certain methods are more efficient and accuratethan others For most mixed continuous and discrete systems the Runge Kutta variable step methods ode23 andode45 are superior to the other methods in terms of efficiency and accuracy Due to discontinuities associated with the sample and hold of the discrete blocks theode15s andode113 methods arenot recommended for mixed continuous and discrete systems 10 15 10 Additional Topics 10 16 Model Construction Commands Introduction 4h ee ue oS eee OR H ow to Specify Parameters for the Commands H ow to Specify a Path for a Simulink Object add_block add_line bdclose bdroot close_system delete_block delete line find_system gcb gcbh gcs get_param new_system open_system replace_block save_system set_param simulink 11 2 a 11 3 11 4 11 5 11 6 11 7 11 8 11 10 11 11 11 12 11 14 11 15 11 16 11 17 11 18 11 19 11 20 11 21 11 22 11 24 11 M odel C onstruction Commands 11 2 Introduction This table indicates the tasks performed by the commands described in this chapter The reference section of this chapter lists the commands in alphabetical order Task Command Create a new system Open an existing system Close a system
341. riginal blocks Sequence numbers are added to the new block names Specifying Block Parameters Certain aspects of a block s function are defined by the block s parameters Y ou can assign values to block parameters on the block s dialog box Double click on the block to open its dialog box You can accept the displayed values or change them You can also use thes et_ param command to change block parameters See Chapter 11 for details 3 Creating a M odel 3 8 The reference material that describes each block in Chapter 9 shows the dialog box and describes the block parameters Deleting Blocks To delete one or more blocks select the blocks to be deleted and press the Delete or Backspace key You can also choose Clear or Cut from the Edit menu The Cut command writes the blocks into the clipboard which enables you to paste them into a model Using the Delete or Backspace key or the Clear command does not enable you to paste the block later You can use the Undo command from the Edit menu to replace a deleted block Changing the Orientation of Blocks By default signals flow through a block from left to right Input ports are on the left and output ports are on the right You can change the orientation of a block by choosing one of these commands from the Format menu e The Flip Block command rotates the block 180 degrees e The Rotate Block command rotates a block clockwise 90 degrees The figure below shows how Sim
342. riting output to return variables and using MATLAB plotting commands e Writing output tothe workspace using To Workspace blocks and plotting the results using MATLAB plotting commands Using the Scope Block You can use display output trajectories on a Scope block during a simulation This simple model shows an example of the use of the Scope block Nee Step Transfer Fen Scope The display on the Scope shows the output trajectory The Scope block enables you to zoom in on an area of interest or save the data to the workspace The XY Graph block enables you to plot one signal against another These blocks are described in Chapter 9 Using Return Variables By returning time and output histories you can use MATLAB plotting commands to display and annotate the output trajectories gt 5 peo Step Transfer Fen an The block labeled Out is an Outport block from the Connections library The output trajectory yout is returned by the integration solver For more information see Chapter 4 You can alsorun this simulation from the Simulation menu by specifying variables for the time output and states on the Workspace I O page of the Simulation Parameters dialog box You can then plot these results using plot tout yout Viewing O utput Trajectories Using the To Workspace Block The To Workspace block can be used to return output trajectories to the MATLAB workspace The model below illustrates this use He co BEE St
343. rkspace The matrix has one column per input element and one row per simulation step Data is not available until the simulation is stopped or paused Parameters Variable name simout Maximum number of rows inf Decimation 1 Sample time 1 Apply Revert Help Sample Time Inherited Vectori zed Yes The name of the matrix that holds the data The maximum number of rows one row per time step to be saved The default is 1000 rows A decimation factor The default is 1 The sample time at which to collect points Transfer Fcn Purpose Library Description Implement a linear transfer function Linear The Transfer F cn block implements a transfer function wheretheinput u and output y can be expressed in transfer function form as the following equation H s y s _ num s _ num 1 s gt 14 num 2 s 74 num nn IT endet ug gee NOES niga u s den s den 1 s den 2 s den nd where nn and nd are the number of numerator and denominator coefficients respectively num and den contain the coefficients of the numerator and denominator in descending powers of s num can bea vector or matrix den must be a vector and both are specified as parameters on the block dialog box The order of the denominator must be greater than or equal to the order of the numerator Block input is scalar output width is equal to the number of rows in the numerator Initial conditions ar
344. rossing signal This signal is not accessible by the block diagram For the Saturation block the signal that is used to detect zero crossings for the upper limitiszcSignal UpperLimit u whereu is the input signal Zero crossing signals have a direction attribute which can have these values e rising a zero crossing occurs when a signal rises to or through zero or when a signal leaves zero and becomes positive e falling azerocrossing occurs when a signal falls toor through Zero or when a signal leaves zero and becomes negative e either a zero crossing occurs if either a rising or falling condition occurs For the Saturation block s upper limit the direction of the zero crossing is either This enables the entering and leaving saturation events to be detected using the same zero crossing signal If the error tolerances are too large it is possible for Simulink to fail to detect a zero crossing For example if a zero crossing occurs within a time step but the values at the beginning and end of the step do not indicate a sign change the solver will step over the crossing without detecting it How Simulink W orks This figure shows a signal that crosses zero In thefirst instance the integrator steps over the event In the second the solver detects the event wane not detected detected If you suspect this is happening tighten the error tolerances to ensure that the solver takes small enough steps F
345. rt 7 10 trigger control signal outputting 7 10 trigger events 7 2 7 8 trigger input 7 8 trigger type parameter 7 9 triggered and enabled subsystems 7 2 7 11 triggered subsystems 7 2 7 8 9 155 Trigonometric Function block 9 157 trim function 5 7 5 13 9 80 truth tables implementing 9 20 U unconnected input ports 9 74 unconnected output ports capping 9 145 undefined parameter error message 6 20 Undo menu item 3 3 UndoDel eteFcn block callback parameter 3 32 Uniform Random Number block 9 158 uniformly distributed random numbers 9 158 Unit Delay block 9 159 compared to Transport Delay block 9 153 Unmask button on Mask Editor 6 9 unresolved link 3 14 unstable simulation results 4 20 Update Diagram menu item 3 11 3 15 3 23 10 14 11 22 updating linked blocks 3 15 updating states 10 11 URL specification in block help 6 25 V variable step S function example 8 23 8 40 variable time delay 9 160 Variable Transport Delay block 9 160 variable step solvers 4 7 4 8 vdp model initial conditions 4 16 using Scope block 9 122 vector length checking 10 2 vector signals displaying 9 121 vector signals generating from inputs 9 101 vector signals separating 9 30 vectorization of blocks 3 11 vertices moving 3 21 viewing output trajectories 5 2 viscous friction 9 24 visibility of Goto tag 9 73 visible icon frame 6 21 1 19 Index 1 20 W algebraic loops 10 7 Wavelet Toolbox 1 9 zero pole form converting to 5 12 w
346. rt time Get simulation stop time Return TRUE if this is a minor time step Return TRUE if this is a major time step Get the type of the current time step either MAJ OR_TIME_STEP or MINOR_TIME_STEP Set to request to stop the simulation Get solver name Get simulation time step size Call to reset the ODE solver when the system undergoes a noncontinuous change Get sample time Set sample time Get sample time offset Set sample time offset Set the time of the next S function call Return TRUE if it is a sample hit Return TRUE if this is the first time the mdl I nitializeConditions is called A Abs block 9 9 zero crossings 10 5 absolute tolerance 4 11 4 24 9 83 simulation accuracy 4 20 absolute value generating 9 9 accuracy of derivative 9 34 accuracy of simulation 4 20 Ada Extension to Real Time Workshop 1 12 Adams Bashforth M oulton PECE solver 4 9 add_ block command 11 4 add line command 11 5 adding block inputs 9 142 blocks 11 4 lines 11 5 additional parameters for S functions 8 25 Algebraic Constraint block 9 10 algebraic equations specifying 9 10 algebraic loops 10 7 detection 10 2 integrator block reset or IC port 9 44 simulation speed 4 20 alignment of blocks 3 6 analysis functions perturbing model 9 80 AnnotationDefaults section of md file B 3 annotations changing font 3 24 creating 3 24 definition 3 24 deleting 3 24 editing 3 24 manipulating with mouse and keyboard 3 27 moving 3 24 using to document
347. rty extracts the value of the named simulation parameter or solver property from the model value simget OptionStructure property extracts the value of the named simulation parameter or solver property from Opti onStructure returning an empty matrix if the value is not specified in the structure property can bea cell array containing the list of parameter and property names of interest If a cell array is used the output is also a cell array You need to enter only as many leading characters of a property name as are necessary to uniquely identify it Case is ignored for property names This command retrieves the options structure for the vdp model options simget vdp This command retrieves the value of the Ref i ne property for the vdp model refine simget vdp Refine sim simset simget 4 29 simget 4 30 Analyzing Simulation Results Viewing Output Trajectories 5 2 Using the Scope Block 4 5 2 Using Return Variables a a a a on 5 2 Using the To Workspace Block 2 2 2 2 a a a nn 5 3 Linearization a 5 4 Equilibrium Point Determination trim 5 7 Linearization Analysis 5 9 Trim Analysis a 5 13 5 Analyzing Simulation Results 5 2 Viewing Output Trajectories Output trajectories from Simulink can be plotted using one of three methods e Feeding a signal into either a Scope or an XY Graph block e W
348. s Inherited from driving block Yes Yes Yes to detect the crossing IC Purpose Library Description m Dialog Box Characteristics Set the initial value of a signal Connections The IC block sets theinitial condition of the signal connected to its output port For example these blocks illustrate how the IC block initializes a signal labeled test signal e test signal 3 Constant Out At t 0 the signal valueis 3 Afterwards the signal valueis 6 The IC block is also useful in providing an initial guess for the algebraic state variables in the loop F or more information see Chapter 10 r Initial Condition m Initial condition for signal Parameters Initial value Apply Revert Help Direct Feedthrough Yes Theinitial value for the signal The default is 1 Sample Time Inherited from driving block Scalar Expansion Parameter only States 0 Vectorized Yes Zero Crossing No 9 77 Inport 9 78 Purpose Library Description g Create an input port for a subsystem or an external input Connections Inports are the links from outside a system into the system Simulink assigns Inport block port numbers according to these rules e t automatically numbers the Inport blocks within a top level system or subsystem sequentially starting with 1 If you add an Inport block it is assigned the next available number If you delete an Inport block other port numbers are
349. s see page 8 45 mdlinitializeSampleTimes Example static void mdl Il nitializeSampleTimes SimStruct S I x Initialize continuous sample time to 0 0 x Initialize offset to 0 0 ssSetSampleTimeEvent S 0 0 0 ssSetOffsetTimeEvent S 0 0 0 Initialize discrete sample time to 0 1 secs x Initialize offset for discrete ST to 0 025 secs ssSetSampleTimeEvent S 1 0 1 ssSetOffsetTi meEvent S 1 0 025 8 59 mdllnitializeSizes Purpose Declaration Arguments Description Example Initializesi zes structure static void mdllnitializeSizes SimStruct 5 SimStruct S Thesimstruct for this block Themdl nitializeSizes function initializes thesi zes structure stored in the Si mSt ruct You define values for thesi zes structure fields using the Si mStruct access macros All undefinedsizes fields are set to zero To specify that certain block characteristics be dependent on the number of inputs to the S F unction block set the value of thesi zes field to 1 or use the DYNAMI CALLY_ SIZED macro For more information about using this function see Defining S Function Block Characteristics on page 8 28 static void mdllnitializeSizes SimStruct 5 ssSetNumContStates Si 2 4 continuous states ssSetNumDiscStates S 1 discrete states ssSetNuml nputs Sa 2 4 inputs ssSetNumOut puts Se 2 outputs ssSetDirectFeedThrough S 0 direct feedthrough
350. s from One Window to Another As you build your model you often copy blocks from Simulink block libraries or other libraries or models into your model window To do this follow these steps 1 Open the appropriate block library or model window 2 Drag the block you want to copy into the target model window To drag a block position the cursor over the block icon then press and hold down the mouse button Move the cursor into the target window then release the mouse button You can also copy blocks by using the Copy and Paste commands from the Edit menu 1 Select the block you want to copy 2 Choose Copy from the Edit menu 3 Makethetarget model window the active window 4 Choose Paste from the Edit menu Simulink assigns a name to each copied block If it is the first block of its type in the model its name is the same as its name in the source window For example if you copy the Gain block from the Linear library into your model window the name of the new block is Gain If your model already contains a block named Gain Simulink adds a sequence number to the block name for example Gainl Gain2 You can rename blocks see Manipulating Block Names on page 3 9 When you copy a block the new block inherits all the original block s parameter values Simulink uses an invisible five pixel grid to simplify the alignment of blocks All blocks within a model snap to a line on the grid You can move a block slightly up down
351. s its signal from the block connected to the top most port on the Subsystem block Inport If you renumber the Port number of an Inport block the block becomes connected to a different input port although the block continues to receive its signal from the same block outside the subsystem The Inport block name appears in the Subsystem block icon as a port label To suppress display of the label select the nport block and choose Hide Name from the Format menu Then choose Update Diagram from the Edit menu Inport Blocks in a Top Level System Inport blocks in a top level system have two uses to supply external inputs from the workspace which you can do by using either the Simulation Parameters dialog box or thes i m command and to provide a means for analysis functions to perturb the model e To supply external inputs from the workspace using the Simulation Parameters dialog box On the Workspace I O tab select the Input check box in the Load from workspace area n the data field specify either the matrix of time and input values or a function that provides input values EJ Simulation parameters untitled _ x Salver Workspace 10 Diagnostics Load kem workspace Save to workspace I Input IV Time tout Select this check Au box to load input sk from the workspace IV Output yout using Inport blocks States I Load initial I Save final Save options T Limit rows to last Decimation 1
352. s structure static void mdll nitializeSizes SimStruct S ssSetNumContStates S 0 number of continuous states ssSetNumDiscStates S 0 number of discrete states ssSetNuminputs S DYNAMICALLY SIZED number of inputs ssSetNumOutputs S DYNAMICALLY_SIZED number of outputs ssSetDirectFeedThrough S 1 direct feedthrough flag ssSetNumSampleTimes S 1 number of sample times ssSetNumSFcnParams S 0 number of extra input param s ssSetNumRWork S 0 number of real work vector elements ssSetNuml Work S 0 number of integer work vector elem s ssSetNumPWork S 0 number of pointer work vector elem s mdl I nitializeSampleTimes initialize sample times array static void mdlIl nitializeSampleTimes SimStruct 5 ssSetSampleTime S 0 NHERI TED SAMPLE TI ME ssSetOffsetTime S 0 0 0 mdlInitializeConditions initialize the states static void mdll nitializeConditions double x0 SimStruct S W riting S Functions as C M EX iles mdi Outputs compute the outputs static void md Outputs double y const double x const double u SimStruct 5 int tid int i nOutputs nOutputs ssGetNumOut put s S for i 0 i lt nQOutputs i y 2 0 U mdi Update perform action at major integration time step static void mdl Update double x const double u SimStruct S int tid
353. sample rate which is related to the correlation time of the noise Theoretically continuous white noise has a correlation time of 0 a flat Power Spectral Density PSD and a covariance of infinity In practice physical systems are never disturbed by white noise although white noise is a useful theoretical approximation when the noise disturbance has a correlation time that is very small relative to the natural bandwidth of the system In Simulink you can simulate the effect of white noise by using a random sequence with a correlation time much smaller than the shortest time constant of the system The Band Limited White Noise block produces such a sequence The correlation time of the noise is the sample rate of the block For accurate simulations use a correlation time much smaller than the fastest dynamics of the system You can get good results by specifying 1 27 te T00Finax where fmax is the bandwidth of the system in rad sec The Algorithm Used in the Block Implementation To produce the correct intensity of this noise the covariance of the noise is scaled to reflect the implicit conversion from a continuous PSD toa discrete noise covariance The appropriate scale factor is 1 t wheret is the correlation time of the noise This scaling ensures that the response of a continuous system to our approximate white noise has the same covariance as the system would have if we had used true white noise Because of this scaling the c
354. scalar or vector 0 sine square sawtooth random scalar or vector 1 scalar or vector 1 Hertz rad sec scalar or vector 1 scalar or vector 1 scalar or vector 0 scalar sample period 1 or vector period offset scalar or vector 1 scalar or vector 0 scalar or vector 1 A 22 M ask Parameters Mask Parameters This section lists parameters that describe masked blocks This table lists masking parameters which correspond to Mask Editor dialog box parameters Table A 9 Mask Parameters Parameter Dialog Box Parameter Values askType Mask type string askDescription Block description string askHel p Block help string askPrompts askPrompt String askStyles askStyleString askVariables askl nitialization askDisplay askl conFrame askl conOpaque aski conRotate askl conUnits askVal ues askValueString Prompt see below Prompt see below Control type see below Control type see below Variable see below Initialization commands Drawing commands Icon frame Visible is on Invisible isoff Icon transparency Opaque is on Transparent is off Icon rotation Rotates is on Fixed isoff Drawing coordinates Block parameter values see below Block parameter values see below cell array of strings delimited string cell array Edit Checkbox Popup Edit Checkbox Popup string MATLAB command display commands on off
355. se and other tasks are described in more detail in Chapter 3 2 13 2 Q uick Start Creating a Model Starting Simulink Selecting Objects Blocks Libraries Lines Signal Labels Annotations Summary of Mouse and Keyboard Actions Creating Subsystems Tips for Building Models Modeling Equations Saving a Model Printing a Block Diagram The Model Browser Ending a Simulink Session 3 17 3 22 3 24 3 25 3 27 3 33 3 34 3 38 3 39 3 42 3 45 3 Creating a M odel Starting Simulink Tostart Simulink you must first start MATLAB Consult your MATLAB documentation if you need more information You can then start Simulink in two ways e Click on the Simulink icon on the MATLAB toolbar e Enter thesi mul i nk command at the MATLAB prompt After MATLAB finishes processing the command your desktop includes the MATLAB command window a new empty model window named untitled and the Simulink block library window shown below Library simulink Oo x Eile Edit la Format Tools BER HHHB Sources Sinks Discrete Linear Nonlinear Connections Blocksets amp Simulink Block Library z Demos Toolboxes Copyright c 1990 97 by The MathWorks Inc The Simulink block library window displays icons that represent the block libraries You build models by copying blocks from block libraries into a model window this procedure is
356. set Scope Scope A 19 A Model and Block Parameters Table A 7 Sinks Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Open If Scope open when the off on model is opened Cannot set from dialog box Grid for future use on off TickLabels Hide tick labels on off ZoomMode Zoom button initially on xonly yonly pressed Ti meRange Time range scalar auto YMin Y min scalar 5 YMax Y max scalar 5 SaveToWorkspace Save data to workspace off on SaveName Limit MaxRows MaxRows Decimation Samplelnput Sampl eTi me Variable name Limit rows to last no label Value if Decimation selected Toggles with Decima tion Samplelnput value variable ScopeDat a on off scalar 5000 scalar 1 off on scalar sample period 0 or vector period offset Stop Simulation St opSi mul ati on no block specific parameters To File ToFile Filename MatrixName Decimation Filename Variablename Decimation filename untitled mat variable ans scalar 1 A 20 Block Specific Parameters Table A 7 Sinks Library Block Parameters Continued Block BlockType Parameter Dialog Box Prompt Values Sampl eTi me Sample time To Workspace To Works pace Vari abl eName Variable name Buffer Maximum number of rows Deci mation Decimation Sampl eTi me Sample time XY Graph XY scope maske
357. sing Inherited from driving block Of parameters and input Yes Yes to detect when the signal reaches a limit and when it leaves the limit Scope Purpose Library Description a Display signals generated during a simulation Sinks The Scope block displays its input with respect to simulation time The block accepts one input and can display up to 30 signals The Scope allows you to adjust the amount of time and the range of input values displayed You can move and resize the Scope window and you can modify the Scope s parameter values during the simulation When you start a simulation Simulink does not open Scope windows although it does write data to connected Scopes As a result if you open a Scope after a simulation the Scope s input signal or signals will be displayed If the signal is continuous the Scope produces a point to point plot If the signal is discrete the Scope produces a stairstep plot The Scope provides toolbar buttons that enable you to zoom in on displayed data display all the data input to the Scope preserve axes settings from one simulation to the next limit data displayed and save data to the workspace The toolbar buttons are labeled in this figure which shows the Scope window as it appears when you open a Scope block EJ Scope Zoom in both x and y directions 19 gall Zoom in x direction Zoom in y direction Auto scale data Save axes settings Properties
358. sion Of inputs Vectorized Yes Zero Crossing Yes to detect when the output changes Relay Purpose Library Description HA Parameters and Dialog Box Characteristics Switch output between two constants Nonlinear The Relay block allows the output to switch between two specified values When the relay is on it remains on until the input drops below the value of the Switch off point parameter When the relay is off it remains off until the input exceeds the value of the Switch on point parameter The block accepts one input and generates one output Specifying a Switch on point value greater than the Switch off point value models hysteresis whereas specifying equal values models a switch with a threshold at that value The Switch on point value must be greater than or equal to the Switch off point r Relay Outputs the specified on or off value by comparing the input to the specified thresholds The on off state of the relay is not affected by input between the upper and lower limits Parameters Switch on point eps Theon threshold for the relay The default iSeps Switch off point eps The off threshold for therelay Thedefaultiseps Output when on 1 The output when the relay is on The default is 1 Output when off 0 Apply Revert Help Direct Feedthrough Yes The output when the relay is off The default is 0 Sample Time Inherited from driving block Sca
359. sistency checking results in a significant decrease in performance up to 40 it should generally be set toof f Use consistency checking to validate your S functions and to help you determine the cause of unexpected simulation results To perform efficient integration Simulink saves caches certain values from one time step for use in the next time step For example the derivatives at the end of a time step can generally be re used at the start of the next time step The solvers take advantage of this to avoid redundant derivative calculations Another purpose of consistency checking is to ensure that blocks produce constant output when called with a given value of t time This is important for the stiff solvers ode23s andodel5s because while calculating the 4 17 4 Running a Simulation 4 18 J acobian the block s output functions may be called many times at the same value of t When consistency checking is enabled Simulink recomputes the appropriate values and compares them to the cached values If the values are not the same a consistency error occurs Simulink compares computed values for these quantities e Outputs e Zero crossings e Derivatives e States Disabling Zero Crossing Detection You can disable zero crossing detection for a simulation For a model that has zero crossings disabling the detection of zero crossings may speed up the simulation but might have an adverse effect on the accuracy of simu
360. ssing Toolbox 1 9 signals 3 17 delaying and holding 9 159 displaying vector 9 121 labeling 3 22 limiting 9 120 limiting derivative of 9 113 passed from Goto block 9 64 passing to From block 9 71 plotting 9 121 9 163 pulses 9 39 9 108 repeating 9 118 vector 3 11 sim command 4 21 4 22 simget command 4 28 simset command 4 24 simsizes function 8 11 SimStruct macros C 2 simulating models 4 22 simulation accuracy 4 20 command line 4 21 menu 4 4 proceeding with suspended 4 5 running 2 12 speed 4 19 stages 8 5 starting 4 4 stopping 2 12 4 5 9 140 suspending 4 5 simulation parameters 4 6 setting 4 4 specifying 2 12 4 4 specifying usingsi mset command 4 24 Simulation Parameters dialog box 2 12 4 4 4 6 4 18 A 3 simulation time compared to clock time 4 7 generating at sampling interval 9 36 outputting 9 19 writing to workspace 4 15 Simulink ending session 3 45 icon 3 2 3 3 menus 3 2 Real Time Workshop 1 10 starting 3 2 windows and screen resolution 3 3 Simulink block library 3 2 opening 11 24 si mul ink command 3 2 11 24 si mul i nk c included in S function 8 28 sine wave generating 9 132 9 134 generating with increasing frequency 9 18 Sine Wave block 9 134 Sinks block library 9 4 block parameters A 19 size of block changing 3 9 sizes structure 8 8 8 11 8 28 dynamically sized fields 8 43 initializing 8 60 setting values 8 29 sizes vector 4 16 slash in block name 11 3 Slider Gain block
361. start of simulation The compile trace flag displays the compilation phases of a block diagram model ZeroCross on off Enable disable location of zero crossings This property applies only to the variable step solvers If set toof f variable step solvers will not detect zero crossings for blocks having intrinsic zero crossing detection The solvers adjust their step sizes only to satisfy error tolerance This command creates an options structure called myopts that defines values for the MaxRows and Refine parameters using default values for other parameters myopts simset MaxRows 100 Refine 2 This command simulates thev dp model for 10 seconds and uses the parameters defined in myopts t x y sim vdp 10 myopts sim simget 4 27 simget 4 28 Purpose Syntax Description Examples See Also Get options structure properties and parameters struct simget model value simget model property Thesi mget command gets simulation parameter and solver property values for the specified Simulink model If a parameter or property is defined using a variablename si mget returns the variable s value not its name If the variable does not exist in the workspace Simulink issues an error message struct simget model returns the current options structure for the specified Simulink model The options structure is defined usingthesi m and simset commands value simget model prope
362. stem points addsasegmentedlinetoa system Each row of the points array specifies the x and y coordinates of a point on a line segment The origin is the top left corner of the window The signal flows from the point defined in the first row to the point defined in the last row If the start of the new lineis close tothe output of an existing block or line a connection is made Likewise if the end of the line is close to an existing input a connection is made This command adds a line to the my mode system connecting the output of the Sine Wave block tothe first input of the Mux block add_line mymodel Sine Wave 1 Mux 1 This command adds a line to the my mode system extending from 20 55 to 40 10 to 60 60 add_line mymodel 20 55 40 10 60 60 delete line 11 5 bdclose 11 6 Purpose Syntax Description Examples See Also Close any or all Simulink system windows unconditionally bdclose bdclose sys bdclose all bdclose with noarguments closes the current system window unconditionally and without confirmation Any changes made to the system since it was last saved are lost bdclose sys closes the specified system window bdclose all closes all system windows This command closes thevdp system bdclose vdp close system new_system open_system save system bdroot Purpose Syntax Description Examples See Also Return the name of the top level Simuli
363. stem S function 8 20 8 37 initial conditions vector defining 8 48 linearization 5 4 masking 6 3 multirate discrete model 10 12 pointer work vector 8 49 return variables 5 2 sample time for continuous block 8 46 sample time for hybrid block 8 47 Scope block 5 2 To Workspace block 5 3 Transfer Function block 3 36 variable step S function 8 23 8 40 Exit MATLAB menu item 2 13 3 45 Expand All menu item 3 43 Expand Library Links menu item 3 43 expressions applying to block inputs 9 61 9 94 external inputs 4 23 external inputs from workspace 9 79 9 80 extracting linear models 5 4 5 9 Extras block library 9 3 F falling trigger 7 8 7 9 Fcn block 9 61 compared to Math Function block 9 93 compared to Rounding Function block 9 119 compared to Trigonometric Function block 9 157 simulation speed 4 19 file reading from 9 66 writing to 4 5 9 146 final states saving 4 15 Financial Toolbox 1 6 find_system command 11 12 finding library block 3 16 finding objects 11 12 Finite Impulse Response filter 9 37 finite state machines implementing 9 20 First Order Hold block 9 63 compared to Zero Order Hold block 9 63 fixed icon rotation 6 21 Index fixed step size 4 10 4 25 Fixed Point Blockset 1 14 fixed step solvers 4 7 4 9 flag parameter 8 6 Flip Block menu item 3 8 3 35 Flip Name menu item 3 10 flip flops implementing 9 20 floating Display block 4 2 9 57 floating Scope block 4 2 9 122 f ohdemo demo 9 63 font annota
364. t is a square wave with an amplitude of 1 and a frequency of 1 rad sec TheIntegrator block integrates its input x to produce x Other blocks needed in this model include a Gain block and a Sum block To generate a square wave use a Signal Generator block and select the Square Wave form but change the default units to radians sec Again view the output using a Scope block Gather the blocks and define the Gain In this model to reverse the direction of the Gain block select the block then usethe Flip Block command from the Format menu Also tocreatethe branch line from the output of the Integrator block to the Gain block hold down the Ctrl key on a Microsoft Windows or X Windows system or the Option key on a Macintosh while drawing the line For more information see Drawing a Branch Line on page 3 18 Now you can connect all the blocks These procedures are discussed earlier in this chapter oooo oo Signal Generator Gain An important concept in this model is the loop that includes the Sum block the Integrator block and the Gain block In this equation xis the output of the 3 35 3 Creating a M odel 3 36 Integrator block It is also the input to the blocks that compute x on which it is based This relationship is implemented using a loop The Scope displays x at each time step F or a simulation lasting 10 seconds the output looks like this EJ Scope DAA Alta 0 1 2
365. t a time by selecting objects located near each other using a bounding box or by selecting the entire model Selecting Multiple Objects One ata Time To select more than one object by selecting each object individually hold down the Shift key and click on each object to be selected To deselect a selected object click on the object again while holding down the Shift key Selecting O bjects Selecting Multiple Objects Using a Bounding Box An easy way to select more than one object in the same area of the window is to draw a bounding box around the objects 1 Define the starting corner of a bounding box by positioning the pointer at one corner of the box then pressing and holding down the mouse button Notice the shape of the cursor H Sine Wawe Scope Drag the pointer to the opposite corner of the box A dotted rectangle encloses the selected blocks and lines Sine Wave Scope Releasethe mouse button All blocks and lines at least partially enclosed by the bounding box are selected a I Sine Wave ke Scope Selecting the Entire Model To select all objects in the active window choose Select All from the Edit menu You cannot create a subsystem by selecting blocks and lines in this way for more information see Creating Subsystems on page 3 27 3 Creating a M odel 3 6 Blocks This section discusses how to perform useful model building actions involving blocks Copying and Moving Block
366. t delays each sample time hit The value of the offset cannot exceed the corresponding sample time A sampletime hit occurs at time values determined by this formula time n sample time value offset wheren is an integer whose first value is zero When a sample time is specified Simulink callsthemd Out put and md Update functions at each sample time hit as defined by the above equation When writing a single rate discrete S function it is not necessary to put explicit tests for sample time hits in your output and update functions Simulink calls your S function only at the appropriate sample hits Refer to either the M file or C MEX file hybrid example page 8 20 and page 8 20 respectively for how to handle multiple sample times Inherited Sample Times Sometimes an S F unction block has no inherent sample time characteristics that is it is either continuous or discrete depending on the sample time of 8 9 8 S Functions 8 10 some other block in the system You can specify that the block s sample time is inherited A simple example of this is a Gain block that inherits its sample time from the block driving it A block can inherit its sample time from e Thedriving block e The destination block e The fastest sample time in the system Toset a block s sample time as inherited use 1 as the sample time For more information on the propagation of sample times see Sample Time Colors on page 10 13
367. t have direct feedthrough The reason for this is that most S functions that do not have discrete states and do have direct feedthrough do not have update functions Therefore Simulink is able to eliminate the need for the extra call in these circumstances If your S function needs to have its md Update routine called and it does not satisfy either of the above conditions specify that it has a discrete state using thessSet NumDiscStates macrointhemdl nitializeSizes function Specifying Sample Times The sample times are stored in an array in theSi mSt ruct and specified in the mdlInitializeSampl eTimes function The value is assigned by the ssSetSampleTi me macro which has this syntax ssSetSampleTime S st_index sample time wheres istheSi mStruct st_index is the index of the sample time being assigned a value the first is 0 the second is 1 and soon and sampl e_ti me is the value associated with the particular st_index Themdl nitializeSizes function must include a call to the macro that specifies the number of sample times defined for the block num ssSetNumSampleTimes S num Sample Times and Input Output Port Widths Sample times can be a function of the input output port widths In mdl I nitializeSampleTimes you can specify that sample times are a function ofssGetNumlnputs andssGetNumOut puts Specifying Offsets The offsets are also stored in a Si mStruct array and specified in the mdl I nitializeSampleTimes
368. t nStates i ylil x i mdlITerminate Purpose Declaration Arguments Description Example Clean up at termination of the simulation static void mdlTerminate SimStruct S SimStruct 5 ThesimStruct for this block The mdi Ter mi nat e function performs any necessary actions upon termination of the simulation such as deallocating memory that was allocated in the mdi nitializeConditions function For an example of the use of the md Ter mi nat e function see Allocating Work Vectors and Setting Their Values on page 8 48 8 63 mdlUpdate Purpose Declaration Arguments Description Major time step update static void md Updat e double x double u SimStruct S int tid double x The states vector both continuous and discrete input and returned double u The input vector SimStruct S Thesimstruct for this block int tid The task ID for use with multitasking real time operating systems The mdi Update function is called once at each major integration step such as for updating the discrete state vector ee The function is also useful for S functions that need to perform some action at each major integration step such as data collection blocks Note that you can also change the values of continuous states in this function An S function s md Update function will be called if and only if the S function has one or more discrete states or does not have direct feedthrough If y
369. t of enabled subsystem 7 4 reset states of enabled subsystem 7 5 resetting state 9 83 resizing blocks 3 9 return variables example 5 2 reversing direction of signal flow 3 35 Revert button on Mask Editor 6 9 right hand approximation 9 43 rising trigger 7 8 7 9 Robust Control Toolbox 1 8 Rosenbrock formula 4 9 Rotate Block menu item 3 8 rotates icon rotation 6 21 Rounding Function block 9 119 Runge Kutta 2 3 pair 4 9 Runge Kutta 4 5 formula 4 8 Runge Kutta fourth order formula 4 9 running the simulation 2 12 S sample model 2 6 sample time 10 11 backpropagating 10 15 changing during simulation 10 11 colors 10 13 constant 10 9 continuous block example 8 46 fundamental 4 8 hybrid block example 8 47 inherited 8 9 offset 10 11 parameter 10 11 S functions specifying in 8 9 8 45 8 58 simulation speed 4 19 Sample Time Colors menu item 10 10 10 13 sample time hit 8 9 sampleand hold applying to block input 9 97 sampleand hold implementing 9 164 Index sampled data systems 10 11 sampling interval generating simulation time 9 36 Saturation block 9 120 zero crossings 10 4 10 6 Save As menu item 3 38 Save menu item 2 13 3 38 save options area 4 15 save to workspace area 4 15 save_system command 3 16 11 21 saving axes settings on Scope 9 125 final states 4 15 4 16 models 2 13 3 38 output to workspace 4 15 systems 11 21 sawtooth wave generating 9 132 scalar expansion 3 11 Scope block 9 121 e
370. tVarHit SimStruct S double u ssGet U S ssSetTNext S ssGetT S u 1 mdi Outputs compute the outputs static void mdl Outputs double y const double gt x const double u SimStruct S int tid y 0 x 0 mdi Update perform action at all time steps 8 41 8 S Functions static void mdIUpdate double x const double u SimStruct S int tid x 0 u 0 mdi Derivatives compute the derivatives static void mdIDerivatives double dx const double x const double u Si mStruct int tid mdi Terminate called when the simulation is terminated static void mdl Terminate SimStruct S ifdef MATLAB MEX FILE ls this being compiled as MEX file include si mulink c MEX file interface mechanism else include cg_sfun h Code generation registration func endif The output of vsfunc is simply the input u delayed by a variable amount of time md Out puts sets the output y equal tostatex md Update sets the state vector x equal tou the input vector This example calls mdi Get Ti meOf Next Var Hit an S function routine that calculates and sets the time of next hit that is the time when isvsfunc is next called In md Get Ti meOf Next Var Hit the macrossGet U is used to get a pointer to the input u Then this call is made ssSetTNext S ssGetT S u 1 The macrossGetT gets the simulation timet The second input to t
371. table Extrapolation is performed outside the table boundaries The row values for the table entered as a vector The vector values must increase monotonically Parameters R iB The column values for the table entered as a TR vector The vector values must increase 1 3 monotonically Table 45 6 16 19 20 10 18 23 The table of output values The matrix size must a BE match the dimensions defined by the Row and Apply Revert Help Column parameters 9 90 Look Up Table 2 D Characteristics Direct Feedthrough Sample Time Scalar Expansion Vectorized Zero Crossing Yes Inherited from driving blocks Of one input if the other is a vector Yes No 9 91 Manual Switch 9 92 Purpose Library Description io k Parameters and Dialog Box Characteristics Switch between two inputs Nonlinear The Manual Switch block is a toggle switch that selects one of its two inputs to pass through tothe output To toggle between inputs double click on the block icon there is no dialog box The selected input is propagated to the output while the unselected input is discarded You can set the switch before the simulation is started or throw it while the simulation is executing to interactiely control the signal flow The Manual Switch block accepts all input types and retains its current state when the model is saved None Direct Feedthrough Yes Sample Time Inherited from driving block Scala
372. tag name is enclosed in square brackets e scoped means that From and Goto blocks using the same tag must bein the same subsystem or in any subsystem below the Goto Tag Visibility block in the model hierarchy A scoped tag name is enclosed in braces global means that From and Goto blocks using the same tag can be anywhere in the model Use local tags when the Goto and From blocks using the same tag name reside in the same subsystem Y ou must use global or scoped tags when the Goto and From blocks using the same tag name reside in different subsystems When you define a tag as global all uses of that tag access the same signal A tag 9 71 Goto defined as scoped can be used in more than one place in the model This example shows a model that uses two scoped tags with the same name A i Subsystem3 iol x File Edit Simulation Format Subsystem1 ojx File Edit Simulation Format 14 1 Goto Tag stadia Visibility E Mo 5 Aubaystamz From Out From Out Subsystem4 Subsystem2 loj x Subystemd Cl x File Edit Simulation Format Sine Wave Goto File Edit Simulation Format Sine Wave Goto Parameters r Goto a nd Dia log Sends signals to From blocks that have the specified tag Box If tag visibility is scoped then a Goto Tag Visibility block must be used to define the visibility of the tag The block icon displays the selected tag name local tags are
373. te sample time Green Second fastest discrete sample time Blue Third fastest discrete sample time Light Blue Fourth fastest discrete sample time Dark Green Fifth fastest discrete sample time Cyan Triggered sample time To understand how this feature works it is important to be familiar with Simulink s Sample Time Propagation Engine STPE The figure below illustrates a Discrete Filter block with asampletimeofTs drivinga Gain block Because the Gain block s output is simply the input multiplied by a constant its output changes at the same rate as the filter In other words the Gain block has an effective sample rate equal to that of the filter s sample rate This is the fundamental mechanism behind the STPE 44221 p Discrete Filter Gain Toenable the sample time colors feature select Sample Time Colors from the Format menu 10 13 10 Additional Topics 10 14 Simulink does not automatically recolor the model with each change you make to it so you must select Update Diagram from the Edit menu to explicitly update the model coloration Toreturn to your original coloring disable sample time coloration by again choosing Sample Time Colors When using sample time colors the color assigned to each block depends on its sample time with respect to other sample times in the model Simulink sets sample times for individual blocks according to these rules Continuous blocks e g Integrator Derivative Transfer Fn etc
374. tegrator Unit Delay Out Here is the code for the M file S function function sys x0 str ts mixedm t x u flag A hybrid system example that implements a hybrid system consisting of a continuous integrator 1 s in series with a unit delay 1 2 Set the sampling period and offset for unit delay dperiod 1 doffset 0 switch flag case 0 Initialization W riting S Functions as M Files sys x0 str ts mdll nitializeSizes dperiod doffset case 1 sys mdIlDerivatives t x u Calculate derivatives case 2 sys md Update t x u dperiod doffset Update disc states case 3 sys mdl Outputs t x u doffset dperiod Calculate outputs case 4 9 sys Unused flags otherwise error unhandled flag numdstr flag Error handling end end of mixedm mdlinitializeSizes Return the sizes initial conditions and sample times for the S function function sys x0 str ts mdll nitializeSizes dperiod doffset Sizes simsizes sizes NumContStates 1 sizes NumDiscStates 1 sizes NumOut puts 1 sizes Numi nputs 1 sizes DirFeedthrough 0 sizes NumSampleTimes 2 sys simsizes sizes x0 ones 2 1 str ts 0 0 sample time dperiod doffset end of mdllnitializeSizes 8 21 8 S Functions 8 22 md Derivatives Compute derivatives for continuous states function sys mdl Derivatives t x u dperiod doffset
375. the absolute tolerance and run it again Compare the results of both simulations If the results are not significantly different you can feel confident that the solution has converged If the simulation misses significant behavior at its start reducetheinitial step size to ensure that the simulation does not step over the significant behavior If the simulation results become unstable over time e Your system may be unstable e If you areusingodel5s you may need to restrict the maximum order to 2 the maximum order for which the solver is A stable or try using theode23s solver If the simulation results do not appear to be accurate e For a model that has states whose values approach zero if the absolute tolerance parameter is too large the simulation will take too few steps around areas of near zero state values Reduce this parameter value or adjust it for individual states in the Integrator dialog box e f reducing the absolute tolerances do not sufficiently improve the accuracy reduce the size of the relative tolerance parameter to reduce the acceptable error and force smaller step sizes and more steps Running a Simulation from the Command Line Running a Simulation from the Command Line Entering simulation commands in the MATLAB command window or from an M file enables you to run unattended simulations You can perform Monte Carlo analysis by changing the parameters randomly and executing simulations in a loop
376. the block s input port disappears which enables the block to be used as a floating Display block Sample Time 1 Apply Revert Help i Sample Time Inherited from driving block Vectori zed Yes The sample time at which to display points Dot Product Purpose Library Description B Dialog Box Characteristics Generate the dot product Linear The Dot Product block generates the dot product of its two input vectors The scalar output y is equal to the MATLAB operation y ul u2 whereul andu2 represent the vector inputs If both inputs are vectors they must be the same length To perform element by element multiplication without summing use the Product block Dot Product m Dot Product mask Inner dot product y sumlul u2 y Help Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion Yes States 0 Vectorized Yes Zero Crossing No 9 59 Enable 9 60 Purpose Library Description Parameters and Dialog Box Characteristics Add an enabling port to a subsystem Connections Adding an Enable block to a subsystem makes it an enabled subsystem An enabled subsystem executes while the input received at the Enable port is greater than zero For more information about enabled subsystems see Chapter 7 At the start of simulation Simulink initializes the states of blocks inside an enabled subsystem to their initial cond
377. the corresponding port s removed from the S F unction block icon The port is removed when the simulation starts or when you choose Update Diagram from the Edit menu Using Function Call Subsystems You can create a triggered subsystem whose execution is determined by logic internal to an S function instead of by the value of a signal A subsystem so 8 51 8 S Functions 8 52 configured is called a function call subsystem To implement a function call subsystems e Inthe Trigger block select function call as the Trigger type parameter e Inthe S function usethessCal System macro to call the triggered subsystem e n the model connect the S F unction block output directly to thetrigger port F unction call subsystems are not executed directly by Simulink The S function determines when to execute the subsystem When the subsystem completes execution control returns to the S function This figure illustrates the interaction between a function call subsystem and an S function mdl Out puts on ssCallSystem S outputElement ee f next statement qg z PE I i function call subsystem F unction call subsystems can only be connected to S functions that have been properly configured to accept them To configure an S function to call a function call subsystem 1 Specify which elements are to execute the function call system in mdl I nitializeSampleTi mes For example ssSetCallSystemOutput S 0 call on 1st
378. the integral is greater than the Upper saturation limit and the input is positive the output is held at the Upper saturation limit To generate a signal that indicates when the state is being limited select the Show saturation port check box A saturation port appears below the block output port as shown on this figure Output Input T Sr Saturation zi Discrete Time Integrator The signal has one of three values e lindicates that the upper limit is being applied e Oindicates that the integral is not limited e 1 indicates that the lower limit is being applied When the Limit output option is selected the block has three zero crossings one to detect when it enters the upper saturation limit one to detect when it enters the lower saturation limit and one to detect when it leaves saturation Resetting the State The block can reset its state to the specified initial condition based on an external signal To cause the block to reset its state select one of the External Discrete Time Integrator reset choices A trigger port appears below the block s input port and indicates the trigger type as shown in this figure Input I Output Reset Esi Discrete Time Integrator Select rising to trigger the state reset when the reset signal has a rising edge Select falling to trigger the state reset when the reset signal has a falling edge Select either to trigger the reset when either a rising or falling signal occurs
379. the library is not open Simulink opens it and selects the library block Getting Information About Library Blocks Use the i bi nfo command to get information about reference blocks in a system The format for the command is libdata li binfo sys wheres ys is the name of the system The command returns a structure of size n by 1 where n is the number of library blocks ins ys Each element of the structure has four fields e Block the block path e Library the library name e ReferenceBl ock the reference block path e LinkStatus thelink status either resolved or unresol ved Lines Lines Signals are carried on lines Each line can carry a scalar or vector signal A line can connect the output port of one block with theinput port of another block A line can also connect the output port of one block with input ports of many blocks by using branch lines Drawing a Line Between Blocks To connect the output port of one block to the input port of another block 1 Position the cursor over the first block s output port It is not necessary to position the cursor precisely on the port The cursor shape changes to a cross hairs gt Constant Gain 2 Press and hold down the mouse button Drag the pointer tothe second block s input port You can position the cursor on or near the port or in the block If you position the cursor in the block the line is connected to the closest input port The cursor shape
380. the simulation when the input is nonzero Thesimulation completes the current time step before terminating If the block input is a vector any nonzero vector element causes the simulation to stop You can use this block in conjunction with the Relational Operator block to control when the simulation stops For example this model stops the simulation when the input signal reaches 10 plosk Relational s 3 Operator Stop Simulation Constant Stop Stops simulation when input is non zero Sample Time Inherited from driving block Vectorized Yes Stop Simulation x Subsystem Purpose Library Description Dialog Box Characteristics Represent a system within another system Connections A Subsystem block represents a system within another system You create a subsystem in these ways e Copy the Subsystem block from the Connections library into your model Y ou can then add blocks to the subsystem by opening the Subsystem block and copying blocks into its window Select the blocks and lines that are to make up the subsystem using a bounding box then choose Create Subsystem from the E dit menu Simulink replaces the blocks with a Subsystem block When you open the block the window displays the blocks you selected adding Inport and Outport blocks to reflect signals entering and leaving the subsystem The number of input ports drawn on the Subsystem block s icon corresponds to the number
381. these rules e t automatically numbers the Outport blocks within a top level system or subsystem sequentially starting with 1 If you add an Outport block it is assigned the next available number If you delete an Outport block other port numbers are automatically renumbered to ensure that the Outport blocks are in sequence and that no numbers are omitted If you copy an Outport block into a system its port number is not renumbered unless its current number conflicts with an Outport block already in the system If the copied Outport block port number is not in sequence you must renumber the block or you will get an error message when you run the simulation or update the block diagram Outport Blocks in a Subsystem Outport blocks in a subsystem represent outputs from the subsystem A signal arriving at an Outport block in a subsystem flows out of the associated output port on that Subsystem block The Outport block associated with an output port on a Subsystem block is the block whose Port number parameter matches the relative position of the output port on the Subsystem block For example the Outport block whose Port number parameter is 1 sends its signal to the block connected to the top most output port on the Subsystem block If you renumber the Port number of an Outport block the block becomes connected to a different output port although the block continues to send the signal to the same block outside the subsystem When you
382. tics Load from workspace Save to workspace T Input IV Time tout I States IV Output yout States I Load initial initial I Save final Fina Save options T Limit rows to last fio Decimation fi Apply Reven Help Close If you specify one variable namein the edit field all output is written to that variable If the system has more than one Outport block the variableis a matrix where each column contains data for a different Outport block The column order matches the order of the port numbers for the Outport blocks If you specify more than one variable name data from each Outport block is written to a different variable For example if the system has two Outport Select this check box to write output to the workspace using Outport blocks Outport Parameters and Dialog Box Characteristics blocks to save data from Outport block 1 tos peed and the data from Outport block 2 todi st you specify speed dist in the Output field To supply external outputs to the workspace using thesi m command You can write output to the workspace using the third return argument t x y sim If the system has more than one Outport block the above command writes y as a matrix with each column containing data for a different Outport block The column order matches the order of the port numbers for the Outport blocks If you specify more than one variable name after the second state argum
383. tion A Of Parameters and Dialog Box Characteristics Read data from a data store Connections The Data Store Read block reads data from a named data store passing the data as output The data was previously initialized by a Data Store Memory block and possibly written to that data store by a Data Store Write block The data store from which the data is read is determined by the location of the Data Store M emory block that defines the data store For moreinformation see page 9 25 Morethan one Data Store Read block can read from the same data store Data Store Read r Data Store Read Reads values from specified data store r Parameters The name of the data store from which this block reads data Data store name IA Sample time A 4 The sample time which controls when the block reads from the data store The default 1 Beeb Root Help indicates that the sample time is inherited Sample Time Continuous or discrete Vectori zed Yes Data Store Write Purpose Library Description A Parameters and Dialog Box Characteristics Write data to a data store Connections The Data Store Write block writes the block input toa named data store Each write operation performed by a Data Store Write block writes over the data store replacing the previous contents The data store to which this block writes is determined by the location ofthe Data StoreM emory block that
384. tion This feature might be useful when you want to save a steady state solution and restart the simulation at that known state You load states by sdecting the Load initial check box and specifying a state vector in the adjacent field If the check box is not selected or the state vector is empty Simulink uses the initial conditions defined in the blocks 4 15 4 Running a Simulation 4 16 You save the final states the values of the states at the termination of the simulation by selecting the Save final check box and entering a variablein the adjacent edit field When the Model Has Multiple States f you want to specify the initial conditions for a model that has multiple states you need to determine the order of the states You can determine a model s initial conditions and the ordering of its states with this command sizes x0 xstord sys 0 wheresys is the model name The command returns e sizes a vector that indicates certain model characteristics Only the first two elements apply to initial conditions si zes 1 is the number of continuous states andsizes 2 isthe number of discrete states Thesi zes vector is described in more detail in Creating General Purpose S F unction Blocks on page 8 42 x0 the block initial conditions xstord a string matrix that contains the full path name of all blocks in the model that have states The order of the blocks in thexstord andx0 vectors are th
385. tion at 1 0 When the input reaches 0 it again engages the output at the opposite end of the deadband 1 A Input engages in positive direction Change in input causes equal change in output 0 8 0 6 0 4 B Input disengages Change oat in input does not affect j output of C Input engages in negative direction Change in input causes equal change in output 0 2 0 4 0 6 D Input disengages Change in input does not affect output 0 8 Backlash Parameters and Dialog Box Characteristics Backlash Backlash Models backlash where the deadband width specifies the amount of play in the system r Parameters Deadband width 1 Initial output 0 Apply Revert Help Direct Feedthrough Yes The width of the deadband The default is 1 The initial output value The default is 0 Sample Time Inherited from driving block Scalar Expansion Yes Vectorized Yes Zero Crossing Yes to detect engagement with lower and upper thresholds 9 15 Band Limited White Noise 9 16 Purpose Library Description att Introduce white noise into a continuous system Sources The Band Limited White Noise block generates normally distributed random numbers that are suitable for use in continuous or hybrid systems The primary difference between this block and the Random Number block is that the Band Limited White Noise block produces output at a specific
386. tion port causing an algebraic loop For an example of this situation see the bounce model When you want to pass the state from one conditionally executed subsystem to another which may cause timing problems For an example of this situation see thec ut ch model You can correct these problems by passing the state through the state port rather than the output port Although the values are the same Simulink generates them at slightly different times which protects your model from these problems You output the block state by selecting the Show state port check box By default the state port appears on the top of the block as shown in this figure Discrete Time Integrator Discrete Time Integrator Limiting the Integral To prevent the output from exceeding specifiable levels select the Limit output check box and enter the limits in the appropriate parameter fields Doing so causes the block to function as a limited integrator When the output is outside the limits the integral action is turned off to prevent integral wind up During a simulation you can change the limits but you cannot change whether the output is limited The output is determined as follows e When the integral is less than the Lower saturation limit and the input is negative the output is held at the Lower saturation limit e When the integral is between the Lower saturation limit and the Upper saturation limit the output is the integral e When
387. tions 3 24 block icons 3 10 block names 3 10 signal labels 3 23 Font menu item 3 10 3 23 Forward Euler method 9 42 Forward Rectangular method 9 42 f printf command 6 17 F requency Domain System Identification Toolbox 1 6 From block 9 64 From File block 9 66 From Workspace block 9 68 fundamental sample time 4 8 Fuzzy Logic Toolbox 1 6 G Gain block 9 70 and algebraic loops 10 7 gain varying during simulation 9 136 Gaussian number generator 9 111 gcb command 11 14 gcbh command 11 15 gcs command 11 16 get_ param command 11 17 checking simulation status 4 21 global Goto tag visibility 9 64 9 71 Go To Library Link menu item 3 16 Goto block 9 71 Goto Tag Visibility block 9 73 graphics on masked block icons 6 18 Ground block 9 74 grouping blocks 3 27 H handle of current block 11 15 handles on selected object 3 4 hardstop demo9 75 held output of enabled subsystem 7 4 held states of enabled subsystem 7 5 Help button on Mask Editor 6 9 help text for masked blocks 6 6 6 25 Heun s method 4 10 Hide Name menu item 3 10 3 29 9 103 Hide Port Labels menu item 3 29 hiding block names 3 10 hierarchy of model 3 33 10 2 Higher Order Spectral Analysis Toolbox 1 7 Hit Crossing block 9 75 zero crossing detection 4 18 zero crossings 10 4 10 6 hybrid block setting sample time 8 47 hybrid system S function example 8 20 8 37 hybrid systems integrating 10 15 linearization 5 10 simulating 10 11 l IC block 9 77 1 7
388. to create custom dialog boxes and icons for your S Function blocks Masked dialog boxes can make it easier to specify additional parameters for S functions For a discussion of additional parameters see Passing Additional Parameters on page 8 25 and 8 3 8 S Functions Specifying Parameter Values Interactively on page 8 43 For more information about masking see Chapter 6 When To Use an S Function The most common use of S functions is to create custom Simulink blocks Y ou can use S functions for a variety of applications induding e Adding new general purpose blocks to Simulink e Incorporating existing C code into a simulation e Describing a system as a mathematical set of equations e Using graphical animations see the inverted pendulum demo penddemo An advantage of using S functions is that you can build a general purpose block that you can use many times in a model varying parameters with each instance of the block How S Functions Work Each block within a Simulink model has the following general characteristics a vector of inputs u a vector of outputs y and a vector of states x as shown by this illustration u x y input states output The state vector may consist of continuous states discrete states or a combination of both The mathematical relationships between the inputs outputs and the states are expressed by the following equations y folt x u output He falt x u der
389. to dialog box entries have string values See Appendix A for a list of model and block parameters find system SearchDepth depth parameter value restricts the search to a specified depth from the top level system The scalar dept h argument is e 1 for blocks and systems contained in the top level system e 2for blocks and systems contained in the top level system and in the children of that system and so on find _system obj where obj is asystem or block path name searches only in the specified object find _system names wherenames isa cell array of system or block path names searches only the objects listed in names This allows the search to be restricted to objects found by previous fi nd_ system calls find system LookUnderMasks on enables you to search within a masked system unless the mask consists only of an icon If the default value off isin effect the search does not extend into masked systems find _system FollowLinks on enables you to follow a link into a library If the default value of f is in effect the search does not extend into linked blocks find_system Examples See Also This command returns a cell array containing the names of all open systems and blocks find system This command returns the names of all open block diagrams open_bd find system Type block diagram This command returns the names of all Goto blocks that are chi
390. to the block does not change Memory Applies a one integration step delay The output is the previous input value Parameters Initial condition 0 The output at the initial integration step Check this box to cause the sample time to be inherited from the driving block T Inherit sample time Apply Revert Help Direct Feedthrough No Sample Time Continuous but inherited if the Inherit sample time check box is selected Scalar Expansion Of the Initial condition parameter Vectorized Yes Zero Crossing No 9 97 MinMax 9 98 Purpose Library Description Parameters and Dialog Box Characteristics Output the minimum or maximum input value Nonlinear The MinMax block outputs either the minimum or the maximum element or elements of the input s You can choose which function to apply by selecting one of the choices from the Function parameter list If the block has one input port the block outputs a scalar that is the minimum or maximum element of the input vector If the block has more than one input port the block performs an element by element comparison of the input vectors Each element of the block output vector is the result of the comparison of the elements of the input vectors MinMax Output min or max of input For a single input operators are applied across the input vector For multiple inputs operators are applied across the inputs Parameters
391. ton instead of holding down the Ctrl key while using the left mouse button Drawing a Line Segment You may want to draw a line with segments exactly where you want them instead of where Simulink draws them Or you might want to draw a line before you copy the block to which the line is connected You can do either by drawing line segments Todraw a line segment you draw a line that endsin an unoccupied area of the diagram An arrow appears on the unconnected end of the line To add another linesegment position the cursor over the end of the segment and draw another segment Simulink draws the segments as horizontal and vertical lines To draw diagonal line segments hold down the Shift key while you draw the lines Lines Moving a Line Segment To move a line segment follow these steps 1 Position the pointer on the segment you want to move Product Constant 2 Press and hold down the mouse button Sine Wave a tH Constant 3 Drag the pointer to the desired location Sine Wawe tn Product 1 fs Constant 4 Release the mouse button Product Product Constant You cannot move the segments that are connected directly to block ports 3 19 3 Creating a M odel 3 20 Dividing a Line into Segments You can divide a line segment into two segments leaving the ends of the line in their original locations Simulink creates line segments and a vertex that joins them To divide a line into segments
392. tor that corresponds to the rounded value of the control input 9 99 Multiport Switch Pa ra meters Multiport Switch a nd Di a log Multi Port Switch Passes through the input signals corresponding to the Box rounded value of the first input r Parameters Number of inputs 3 Apply Revert Help Characteristics Direct Feedthrough Yes The number of switch inputs to the block Sample Time Inherited from driving block s Scalar Expansion Yes Vectori zed Yes Zero Crossing No 9 100 Mux Purpose Library Description mx p Combine several input lines into a vector line Connections The Mux block combines several input lines into one vector line Each input line can carry a scalar or vector signal The output of a Mux block is a vector If you define the Number of inputs parameter as a scalar Simulink determines the input widths by checking the output ports of the blocks feeding the Mux block If any input is a vector all of its elements are combined by the block If it is necessary to define input widths explicitly you can specify them as a vector Include elements with 1 values for those inputs whose widths are to be determined dynamically during the simulation If an input signal width does not match the expected width Simulink displays an error message For example 4 1 2 indicates three inputs forming a seven element output vector the first four output elements ar
393. tor x and input vector u To obtain a continuous model approximation of a discrete system set Ts to0 For systems composed of linear multirate discrete and continuous blocks dl i nmod produces linear models having identical frequency and time responses for constant inputs at the converted sampling timeTs provided that e Ts isan integer multiple of all the sampling times in the system e Ts isnot less than the slowest sample time in the system e The system is stable It is possible for valid linear models to be obtained when these conditions are not met Computing the eigenvalues of the linearized matrix Ad provides an indication of the stability of the system The system is stable if Ts gt 0 and the eigenvalues are within the unit circle as determined by this statement all abs eig Ad lt 1 Likewise the system isstableifTs 0 and the eigenvalues arein the left half plane as determined by this statement all real eig Ad lt 0 Linearization Analysis When the system is unstable and the sample time is not an integer multiple of the other sampling times dl i nmod produces Ad and Bd matrices which may be complex The eigenvalues of theAd matrix in this case still however providea good indication of stability You can used i nmod to convert the sample times of a system to other values or to convert a linear discrete system to a continuous system or vice versa The frequency response of a continuous or dis
394. tore Connections The Data Store Memory block defines and initializes a named shared data store which is amemory region usable by the Data Store Read and Data Store Write blocks Each data store must be defined by a Data Store Memory block The location of the Data Store Memory block that defines a data store determines the Data Store Read and Data Store Write blocks that can access the data store e If the Data Store Memory block is in the top level system the data store can be accessed by Data Store Read and Data Store Write blocks located anywhere in the model e f the Data Store Memory block is in a subsystem the data store can be accessed by Data Store Read and Data Store Write blocks located in thesame subsystem or in any subsystem below it in the model hierarchy You initialize the data store by specifying values in the Initial value parameter The size of the value determines the size of the data store An error occurs if a Data Store Write block does not write the same amount of data Data Store Memory r DataStoreMemory Defines a memory region for use by the Data Store Read and Data Store Write blocks Parameters The name of the data store being defined The default is A Data store name Initial value 0 Apply Revert Help Sample Time N A Vectorized Yes The initial values of the data store The default value is 0 9 25 Data Store Read 9 26 Purpose Library Descrip
395. uct stores essential size information about the S Function block including the number of inputs outputs states and other block characteristics Thesi zes structure is initialized in the mdlInitializesizes function Supplied macros set values for the structure fields If a value is not specified it is initialized to zero The table below describes the fields in thesi zes structure and indicates the macros used to define values for the fields Table 8 4 sizes Structure Fields Structure Field Macro that Sets Value Number of continuous ssSetNumCont States S numCont States states Number of discrete states ssSetNumDiscStates S numDiscStates Number of outputs ssSetNumOutputs S numOut puts Number of inputs ssSet Numi nputs S num nputs Flag for direct feedthrough ssSetDirectFeedThrough S dirFeedThru Number of sample times ssSetNumSampleTimes S numSampl eTi mes Number of input arguments ssSetNuminputArgs S numl nput Args Number of integer work ssSetNuml Wor k S numl Work vector elements W riting S Functions as C MEX Files Table 8 4 sizes Structure Fields Continued Structure Field Macro that Sets Value Number of real work vector ssSet NumRWork S numRWor k elements Number of pointer work ssSet NumP Wor k S numP Wor k vector elements There are additional macros that get various values F or a complete list of built in macros that work with C language S functions see Appendix C
396. ules and relationships specified in natural language Systems can be simulated in Professional Application Toolboxes MATLAB or incorporated into a Simulink block diagram with the ability to generate code for stand alone execution The Higher Order Spectral Analysis Toolbox The Higher Order Spectral Analysis Toolbox by J erry Mendel C L Max Nikias and Ananthram Swami provides tools for signal processing using higher order spectra These methods are particularly useful for analyzing signals originating from a nonlinear process or corrupted by non Gaussian noise The Image Processing Toolbox The Image Processing Toolbox contains tools for image processing and algorithm development It includes tools for filter design and image restoration image enhancement analysis and statistics color geometric and morphological operations and 2 D transforms The LMI Control Toolbox The LMI Control Toolbox authored by leading researchers Pascal Gahinet Arkadi Nemirovski and Alan Laub allows oneto efficiently solve Linear Matrix Inequalities LMIs LMIs are special convex optimization problems that arise in many disciplines including control identification filtering structural design graph theory and linear algebra TheLMI Control Toolbox also features a variety of LMI based tools for control systems design and covers applications such as robust stability and performance analysis robust gain scheduling and multi objective contro
397. ulink orders ports after changing the orientation of a block using the Rotate Block and Flip Block menu items The text in the blocks show their orientation 1 2 3 V V V oo Down IN 1 gt 4 lt 1 Rotate Left Right 2 gt to lt Flip t K2 3 Right l Left 3 Rotate ap ao NA 1 2 A Blocks Resizing Blocks To change the size of a block select it then drag any of its selection handles While you hold down the mouse button a dotted rectangle shows the new block size When you release the mouse button the block is resized For example the figure below shows a Signal Generator block being resized The lower right handle was selected and dragged to the cursor position When the mouse button is released the block takes its new size This figure shows a block being resized Signal Benerator i Manipulating Block Names All block names in a model must be unique and must contain at least one character By default block names appear below blocks whose ports are on the sides and to the left of blocks whose ports are on the top and bottom as this figure shows gt Topto voten 17 v Left to right Changing Block Names You can edit a block name in one of these ways e To replace the block name on a Microsoft Windows or X Windows system click on the block name then double click or drag the cursor to select the entire name Then enter the new name On a Maci
398. um of the interval The default is 1 Maximum 1 The starting seed for the random number Initial seed 0 generator The default is 0 Sample time 0 The sample period The default is 0 Apply Revert Help Sample Time Continuous discrete or inherited Scalar Expansion No Vectori zed Yes Zero Crossing No Unit Delay Purpose Library Description Parameters and Dialog Box Characteristics Delay a signal one sample period Discrete The Unit Delay block delays and holds its input signal by one sampling interval If the input to the block is a vector all elements of the vector are delayed by the same sample delay This block is equivalent to the z discrete time operator If an undelayed sample and hold function is desired use a Zero Order Hold block or if a delay of greater than one unit is desired use a Discrete Transfer Fn block See the description of the Transport Delay block for an example that uses the Unit Delay block Unit Delay r Unit Delay een The block output for the first simulation period during which the output of the Unit Delay block is undefined Careful selection of this parameter can minimize unwanted output behavior during this time The default is 0 Parameters Initial condition Sample time 1 Apply Revert Help Direct Feedthrough No The time interval between samples The default is 1 Sample Time Discrete Scalar Expansion Of the Initial
399. unction You allocate memory referenced by pointer work vectors in the md nitializeConditions function and free the memory in the md Ter mi nate function An Example Involving a Pointer Work Vector This example opens a file and stores the FILE pointer in the pointer work vector 8 49 8 S Functions 8 50 Thestatement below includedinthemd Inititali zeSi zes function indicates that the pointer work vector is to contain one element ssSetNumPWork S 1 pointer work vector The code below uses the pointer work vector to store a FILE pointer returned from the standard I O function f open static void mdllnitilzeConditions double x0 SimStruct 5 void PWork ssGet PWork S FILE f Ptr fPtr fopen file data r PWork 0 f Ptr This code retrieves the FILE pointer from the pointer work vector and passes it tof cl ose toclose the file static void mdl Terminate SimStruct S void PWork ssGet PWork S FILE fPtr fPtr PWork 0 if fPtr NULL fclose fPtr PWork 0 NULL Nonsampled Zero Crossings for Continuous S Functions Continuous S functions can register nonsampled zero crossings which are used to hone in on state events i e discontinuities in the first derivative of some signal usually a function of an input to your S function To register nonsampled zero crossings set the number of nonsampled Zero crossings in mdi I nitializeSizes using ssSetNu
400. uous Scalar Expansion Of the initial conditions States Depends on the size of A Vectori zed Yes Zero Crossing No 9 138 Purpose Library Description LI Parameters and Dialog Box Characteristics Generate a step function Sources The Step block provides a step between two definable levels at a specified time If the simulation time is less than the Step time parameter value the block s output is the Initial value parameter value For simulation time greater than or equal to the Step time the output is the Final value parameter value The Step block generates a scalar or vector output depending on the length of the parameters The time in seconds when the output jumps from the Initial value parameter to the Final value parameter The default is one second r Step Outputs a step r Parameters Step time 1 The block output until the simulation time reaches the Step time parameter The default is 0 Initial value 0 Final value 1 Apply Revert Help The block output when the simulation time reaches and exceeds the Step time parameter The default is 1 Sample Time Inherited from driven block Scalar Expansion Of parameters Vectorized Yes Zero Crossing Yes to detect step times 9 139 Stop Simulation Purpose Library Description Dialog Box Characteristics 9 140 Stop the simulation when the input is nonzero Sinks The Stop Simulation block stops
401. us so set ts to 0 and its offset to 0 ts 0 0 end mdllnitializeSizes md Derivatives Return the derivatives for the continuous states function sys mdi Derivatives t x u A B C D Sys Axx Bxu end md Derivatives mdi Outputs Return the block outputs function sys mdl Outputs t x u A B C D sys C x Dau end mdi Out puts The above example conforms to the simulation stages discussed earlier in this chapter Unliketi mest wo m this example invokes mdi Derivatives to calculate the derivatives of the continuous state variables whenf ag 1 The system state equations are of the form x Ax Bu y Cx Du so that very general sets of continuous differential equations can be modeled usingcsfunc m Notethat csfunc mis similar to the built in State Space block This S function can be used as a starting point for a block that models a state space system with time varying coefficients 8 17 8 S Functions Example Discrete State S Function Simulink includes a function called ds f unc m which is an example of a discrete state system modeled in an S function This functionissimilar tocs func m the continuous state S function example The only difference is that mdl Update is called instead of mdi Deri vative mdl Update updates the discrete states when theflag 2 Notethat for asingle rate discrete S function Simulink calls the md Update mdl Out put andmdl Get Ti meOf Next Var Hit if
402. using the syntax triml sys x0 u0 y0 ix iu iy The integer vectorsi x iu andi y single out elements in x0 u0 and y0 tobe fixed Because there is no guarantee of a solution point the method finds steady state values that minimize the maximum value of abs x ix x0 ix u iu ud iu yliy yO iy tri m uses a constrained optimization method which restricts the state derivatives to be zero and solves a minimax problem formed from the desired values for x u andy It is possible that no feasible solution exists to this problem in which caset ri m minimizes the worst case deviation from zero of the state derivatives 5 13 Trim Analysis Examples Example 1 5 14 To fix the derivatives to nonzero values use x u y dx trim sys x0 u0 y0 ix iu iy dx0 idx where dx0 represents the desired derivative values andi dx indexes the elements in dx to be fixed Thetrim command takes an optional argument opt i ons used with optimization routines Theo pt ions argument is described in detail in the documentation for the Optimization Toolbox Consider a linear state space model xX Ax Bu y Cx Du The A B C and D matrices are as follows in a system called sys A 0 09 0 01 1 0 B 0 1 0 2 c 0 2 1 5 D 3 0 1 0 Tofind an equilibrium point use x u y dx options trim sys The number of iterations taken is options 10 ans 7 Trim Analysis Example 2 To
403. ut 2 Input vector Output Mux Combinatorial Logic The table below indicates the combination of inputs that generate each output The input signal labeled Input 1 corresponds to the column in the table labeled Input 1 Similarly the input signal Input 2 corresponds to the column Combinatorial Logic with the same name The combination of these values determines which row of the Output column of the table gets passed as block output For example if the input vector is 1 0 the input references the third row 2 1 1 So the output value is 0 Row Input 1 Input 2 Output 1 0 0 0 2 0 1 0 3 1 0 0 4 1 1 1 Example of Circuit This sample circuit has three inputs the two bits a and b to be summed and a carry in bit c It has two outputs the carry out bit c and the sum bit s Hereis the truth table and the outputs associated with each combination of input values for this circuit Inputs Outputs a b c c s 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 1 1 1 0 1 0 0 0 1 1 0 1 1 0 1 1 0 1 0 1 1 1 1 1 9 21 Combinatorial Logic 9 22 Parameters and Dialog Box Characteristics Toimplement this adder with the Combinatorial Logic block you enter the 8 by 2 matrix formed by columns c and s as the Truth table parameter Sequential circuits that is circuits with states can also be implemented with the Combinatorial Logic block by including an additional input for the state of the blo
404. ut components The matrix must have two or more columns The first column must contain monotonically increasing time points Other columns contain data points that correspond to the time point in that row The matrix is expected to have this form ti uly un to ul un tfinal Uleinal UNfinal To input data written by a To Workspace block requires that time be added to the matrix For more information see the description of the To Workspace block on page 9 148 The block uses the time data to determine its output but does not output it This means that for a matrix containing n columns the block outputs a vector of length n 1 consisting of data from all but the first column of the appropriate row If an output valueis needed at atime that falls between two values the output is linearly interpolated between the two time values that bracket the required time If the required time is less than the first or greater than the last time value in the matrix Simulink extrapolates using the first or last two points If the matrix includes two or more rows at the same time value the output is the data point for the first row encountered F or example for a matrix that has this data time values 0122 data points 23 45 At time 2 the output is 4 the data point for the first column encountered at that time value From Workspace Parameters and Dialog Box Characteristics From Workspace r From Workspa
405. ut elements Represent a system within another system Terminate an unconnected output port Add a trigger port to a subsystem Output the width of the input vector Abs Purpose Library Description a Dialog Box Characteristics Output the absolute value of the input Nonlinear The Abs block generates as output the absolute value of the input The block accepts one input and generates one output J twee Direct Feedthrough Yes Sample Time Inherited from driving block Scalar Expansion N A Vectorized Yes Zero Crossing Yes to detect zero 9 9 Algebraic Constraint 9 10 Purpose Library Description Solve re en Parameters and Dialog Box Constrain the input signal to zero Nonlinear The Algebraic Constraint block constrains the input signal f z to zero and outputs an algebraic state z The block outputs the value necessary to produce a zero at the input The output must affect the input through some feedback path This enables you to specify algebraic equations for index 1 differential algebraic systems DAEs By default the Initial guess parameter is zero You can improve the efficiency of the algebraic loop solver by providing an Initial guess of the algebraic state z that is close to the solution value For example the model below solves these equations z2 zl 1 22 z1 1 The solution is z2 1 z1 0 as the Display blocks show 22421 1 Solve 21
406. ut toa file or tothe workspace or if you select output options on the Simulation Parameters dialog box Simulink writes the data when the simulation is terminated or suspended 4 5 4 Running a Simulation The Simulation Parameters Dialog Box This section discusses the simulation parameters which you specify either on the Simulation Parameters dialog box or usingthes i mandsi mset commands described later in this chapter Parameters are described as they appear on the dialog box pages This table summarizes the actions performed by the dialog box buttons which appear on the bottom of each dialog box page Table 4 1 Simulation Parameters Dialog Box Buttons Button Action Apply Applies the current parameter values and keeps the dialog box open During a simulation the parameter values are applied immediately Revert Changes the parameter values back to the values they had when the dialog box was most recently opened and applies the parameters Help Displays help text for the dialog box page Close Applies the parameter values and closes the dialog box During a simulation the parameter values are applied immediately The Solver Page The Solver page appears when you first choose Parameters from the Simulation menu or when you select the Solver tab The Solver page allows you to e Set the simulation start and stop times e Choose the solver and specify its parameters e Select output options The Simul
407. ut vector width and the values of the elements of the parameter You can explicitly size output signals or let Simulink determine their widths e f the Number of outputs vector elements are all positive values the block generates signals with the specified widths In this model the input signal is avector of width 7 and the Number of outputs parameter is 2 4 1 Terminator width Constant Number of outputs 241 Width2 Terminator If the Number of outputs vector elements include positive and 1 values the block generates output signals with the specified widths for those outputs having positive values and dynamically sizes those outputs having 1 values In this model the input signal is a vector of width 7 and the Number of outputs parameter is 1 3 1 Inthis example Simulink explicitly generates a 3 element vector signal as the second output and dynamically 9 31 Demux 9 32 Parameters and Dialog Box sizes the other two outputs by dividing the remaining input elements as evenly as possible In this case the four elements divide equally Terminator width Terminator Constant Number of outputs width1 13 1 Width2 Terminator In the next example the Number of outputs is specified as 1 4 1 This parameter causes Simulink to generate unequal output vectors Terminator width width1 Terminatori Constant Number of outputs 14 1 Width2 Terminato
408. utputs 8 33 8 S Functions 8 34 static void md Outputs double y const double xx const double u SimStruct S int tid y Cx Du y 0 CLO 0 x 0 CLO 1 x 1 D 0 0 ul 0 D 0 1 ul 1 y 1 CL 0 xf 0 CL 1 1 xf 1 DL 1 0 sul 0 D 1 1 sul 1 mdi Update perform action at major integration time step static void mdl Update double const double u SimStruct S int tid mdi Derivatives compute the derivatives static void mdli Derivatives double dx contst double const double u SimStruct S int tid xdot Ax Bu dx 0 ALO 0 x 0 A O 1 x 1 B 0 0 uf 0 B 0 1 u 1 dx 1 AL1 0 x 0 A 1 1 x 1 B 1 0 u 0 B 1 1 u 1 mdli Terminate called when the simulation is terminated static void mdlTerminate SimStruct S ifdef MATLAB MEX_FILE ls this being compiled as MEX file include si mulink c MEX file interface mechanism else include cg _sfun h Code generation registration func endi f This MEX file is the C language version of cs func m the M file code that implements a continuous state model The derivative of the state vector x is calculated in md Deri vati ve and the output y is calculated in md Out puts W riting S Functions as C M EX iles md Update and md Ter mi nate are empty functions because there are no
409. utting minimum or maximum 9 98 passing through stair step function 9 109 piecewise linear mapping 9 87 9 89 plotting 9 163 reading from file 9 66 scalar expansion 3 11 S functions 8 13 sign of 9 131 vector or scalar 3 11 width of 9 162 inserting mask prompts 6 11 integration block input 9 81 discrete time 9 42 Integrator block 9 81 algebraic loops 10 7 example 3 35 sample time colors 10 15 simulation speed 4 20 Index zero crossings 10 6 invariant constants 10 9 invisible icon frame 6 21 J J acobian matrices 4 9 J acobians 5 9 K keyboard actions summary 3 25 keyboard command 6 16 L labeling signals 3 22 labeling subsystem ports 3 29 left hand approximation 9 42 i bi nfo command 3 16 libraries 3 13 3 16 creating 3 13 modifying 3 14 library block definition 3 13 library block finding 3 16 library blocks getting information about 3 16 library definition 3 13 limit rows to last check box 4 15 limiting derivative of signal 9 113 integral 9 82 signals 9 120 line segments 3 18 creating 3 20 diagonal 3 18 moving 3 19 line vertices moving 3 21 Line Widths menu item 3 21 Linear block library 9 5 block parameters A 14 linear models extracting 5 4 5 9 linearization 5 4 5 9 discrete time systems 5 10 linearized matrix eigenvalues 5 10 lines 3 17 3 21 adding 11 5 branch 3 18 3 35 carrying the same signal 2 11 connecting to input ports 2 11 deleting 11 11 diagonal 3 17 dividing into segm
410. ween two constants The Simulink Block Libraries Table 9 5 Nonlinear Library Blocks Continued Block Name Purpose Rounding Function Saturation S Function Sign Switch Transport Delay Trigonometric F unction Variable Transport Delay Perform a rounding function Limit the range of a signal Access an S function Indicate the sign of the input Switch between two inputs Delay the input by a given amount of time Perform a trigonometric function Delay the input by a variable amount of time Table 9 6 Connections Library Blocks Block Name Purpose Data Store Memory Data Store Read Data Store Write Demux Enable From Goto Goto Tag Visibility Ground IC Inport Define a shared data store Read data from a shared data store Write data to a shared data store Separate a vector signal into output signals Add an enabling port to a subsystem Accept input from a Goto block Pass block input to From blocks Define the scope of a Goto block tag Ground an unconnected input port Set the initial value of a signal Create an input port for a subsystem or an external input 9 7 9 Block Reference Table 9 6 Connections Library Blocks Continued Block Name Purpose Mux Outport Selector Subsystem Terminator Trigger Width Combine several input lines into a vector line Create an output port for a subsystem or an external output Select inp
411. which the signal is coming into the system Apply Revert Help Characteristics SampleTime Inherited from driving block Vectorized Yes 9 80 Integrator Purpose Library Description Integrate a signal Linear Thelntegrator block integrates its input The output of theintegrator is simply its state the integral The Integrator block allows you to e Define initial conditions on the block dialog box or as input to the block e Output the state e Define upper and lower limits on the integral e Reset the state depending on an additional reset input Use the Discrete Time Integrator block described on page 9 42 when constructing a purely discrete system Defining Initial Conditions You can define the initial conditions as a parameter on the block dialog box or input them from an external signal To define the initial conditions as a block parameter specify the Initial condition source parameter as internal and enter the value in the Initial condition parameter field To provide the initial conditions from an external source specify the Initial condition source parameter as external An additional input port appears under the block input as shown in this figure Input 1 Initial condition Output Integrator Using the State Port In two known situations you must use the state port instead of the output port e When the output of the block is fed back into the block through the reset port or the initial co
412. with intercept is referred to as the Intercept parameter The slope and intercept are defined as edit controls This means that the user types values into edit fields in the mask dialog box These values are stored in variables in the mask workspace described on page 6 14 Masked blocks can access variables only in the mask workspace In this example the value entered for the slope is assigned to the variable m The Slope block in the masked subsystem gets the value for the slope parameter from the mask workspace This figure shows how theslope parameter definitions in the Mask Editor map to the actual mask dialog box parameters m SampleMaskedBlock mask Models the equation for a line y mx b The slope and intercept are mask block parameters Parameters Slope 3 Prompt Type Variable Intercept Apply Revert Help f After you have created the mask parameters for slope and intercept press the Close button Then double click on the Subsystem block to open the newly constructed dialog box Enter 3 for the Slope and 2 for the Intercept parameters lt lt end of parameter list gt gt 6 5 6 Using M asks to Customize Blocks Creating the Block Description and Help Text The mask type block description and help text are defined on the Documentation page F or this sample masked block the page looks like this EJ Mask Editor samplemask mx b oI x Documentation I
413. x any of the states iu Don t fix the input iy 12 Fix both output 1 and output 2 Invokingtrim returns the solution Your results may differ due to roundoff error x u y dx trim mod x u y ix iu iy X 0 0000 1 0000 1 0000 us 2 1 0000 1 0000 5 7 5 Analyzing Simulation Results dx 1 0e 015 x 0 2220 0 0227 0 3331 Note that there may be no solution to equilibrium point problems If that is the case tri m returns a solution that minimizes the maximum deviation from the desired result after first trying to set the derivatives to zero For a description of thet ri m syntax see page 5 13 Linearization Analysis Purpose Syntax Arguments Description Extract the linear state space model of a system around an operating point A B C D linfun sys A B C D linfun sys x u A B C D linfun sys x u pert A B C D linfun sys x u pert xpert upert linfun linmod dlinmod Orlinmod2 Sys The name of the Simulink system from which the linear model is to be extracted x andu The state and the input vectors If specified they set the operating point at which the linear model is to be extracted pert Optional scalar perturbation factor used for both x andu If not specified a default value of 1e 5 is used xpert and Optional vectors that explicitly set perturbation levels for upert individual states and inputs If specified the pert argument is igno
414. xample 3 36 5 2 properties 9 126 scoped Goto tag visibility 9 64 9 71 Select All menu item 3 5 selecting model 3 5 more than one object 3 4 one object 3 4 Selector block 9 128 separating vector signal 9 30 sequence numbers on block names 3 6 3 7 sequence of signals 9 39 9 108 9 118 sequential circuits implementing 9 22 Set Font dialog box 3 10 set_ param command 3 16 11 22 running a simulation 4 21 setting parameter values 11 22 S Function block 8 2 9 129 general purpose 8 42 multirate 8 46 S Function parameter field 8 43 S functions additional parameters 8 25 block characteristics 8 28 C MEX files 8 2 8 26 C MEX files names 8 7 definition 8 2 input arguments for M files 8 13 MEX file bottom of file 8 27 MEX file top of file 8 27 M files 8 11 output arguments for M files 8 13 parameters 8 43 purpose 8 4 routines 8 6 templates 8 7 sfuntmpl c template 8 7 8 26 8 27 sfunt mp m template 8 7 8 11 Shampine L F 4 9 shared data store 9 25 9 26 9 27 Show Browser menu item 3 42 Show Name menu item 3 10 show output port Enable block 7 5 Trigger block 7 10 showing block names 3 10 Sign block 9 131 zero crossings 10 6 signal flow through blocks 3 8 Signal Generator block 9 132 signal labels changing font 3 23 copying 3 22 creating 3 22 deleting 3 22 1 15 Index editing 3 22 manipulating with mouse and keyboard 3 26 moving 3 22 propagation 3 23 using to document models 3 33 Signal Proce
415. y are implemented as C subroutines The names of the S function routines and the functions they perform are identical in M file and C ME X file S functions For an M file S function Simulink passes af ag parameter tothe S function Theflag indicates the current simulation stage You must write M code that calls the appropriate functions for each flag value For aC MEX file Introduction S function Simulink calls the S function routines directly This table lists the simulation stages the corresponding S function routines and the associated flag value for M file S functions Table 8 1 Simulation Stages Simulation Stage S Function Routine Flag M File S Functions Initialization mdlInitializeSizes flag 0 Calculation of next sample mdi Get Ti meOf Next VarHit flag 4 hit optional Calculation of outputs mdl Outputs flag 3 Update discrete states mdi Update flag 2 Calculation of derivatives md Derivatives flag 1 End of simulation tasks mdi Terminate flag 9 C MEX file S function routines must have exactly the names shown in the figure above In M file S functions you must provide code that based on the flag value calls the appropriate S function routine A template M file S fundion sf unt mpl m is located in tool box si mulink blocks This template uses as wi t ch statement tohandlethef ag values All you have todo is place your code in the correct S function routine In C MEX file S functions
416. y initialization commands e The Icon page enables you to define the block icon e The Documentation page enables you to define the mask type and specify the block description and the block help Five buttons appear along the bottom of the Mask Editor e The Apply button creates or changes the mask using the information that appears on all masking pages The Mask Editor remains open e The Revert button refreshes the page replacing all field values with the information that appeared when the Mask Editor was most recently opened All mask parameters on all Mask Editor pages revert totheir original values e The Unmask button deactivates the mask and closes the Mask Editor The mask information is retained so that the mask can be reactivated To reactivate the mask select the block and choose Create Mask The Mask Editor opens displaying the previous settings The inactive mask information is discarded when the model is closed and cannot be recovered e The Help button displays the contents of this chapter e The Close button applies the mask settings on all pages and closes the M ask Editor Tosee the system under the mask without unmasking it select the Subsystem block then choose Look Under Mask from the Edit menu This command opens the subsystem The block s mask is not affected 6 9 6 Using M asks to Customize Blocks 6 10 The Initialization Page The mask interface enables the user of the masked system to enter
Download Pdf Manuals
Related Search
Related Contents
Hoja de Seguridad Mode d`emploi – ChromoQuant QF Ver.4.0 BDA7501 - Shopify 78K0R/RL78 Real-time OS RI78V4 V1.00.02 PDF do manual do utilizador Enseignement du français langue étrangère Warehouse of Tiffany RL8062 Instructions / Assembly Biostar T41 HD Owner's Manual 製品組立・取扱説明書 Copyright © All rights reserved.
Failed to retrieve file