ModelingSimulationImplementationWriting S-FunctionsVersion 3
1 Overview of S-Functions1-4When to Use an S-FunctionThe most common use of S-functions i s to create custom Simulink blocks. Youcan use S -functions
3 Writing S-Functions As C-MEX files3-56Examples of C MEX-File S-Function BlocksMost S-Function blocks require the handling of states, continuous or d
Examples of C MEX-File S-Function Blocks3-57during which it calls mdlOutputs and mdlDerivatives. Each of these pairs ofcallsisreferredtoasanintegratio
3 Writing S-Functions As C-MEX files3-58matlabroot/simulink/src/csfunc.c/* File : csfunc.c * Abstract: * * Example C-MEX S-function for defi
Examples of C MEX-File S-Function Blocks3-59 return; /* Parameter mismatch will be reported by Simulink. */ } ssSetNumContStates(S, 2);
3 Writing S-Functions As C-MEX files3-60static void mdlOutputs(SimStruct *S, int_T tid){ real_T *y = ssGetOutputPortRealSignal(S,0);
Examples of C MEX-File S-Function Blocks3-61Example - Discrete State S-FunctionThe matlabroot/simulink/src/dsfunc.c example shows how to model adiscre
3 Writing S-Functions As C-MEX files3-62matlabroot/simulink/src/dsfunc.c/* File : dsfunc.c * Abstract: * * Example C MEX S-function for defi
Examples of C MEX-File S-Function Blocks3-63 return; /* Parameter mismatch will be reported by Simulink */ } ssSetNumContStates(S, 0);
3 Writing S-Functions As C-MEX files3-64/* Function: mdlOutputs ======================================================= * Abstract: * y = Cx + Du
Examples of C MEX-File S-Function Blocks3-65Example - Hybrid System S-FunctionsThe S-function, matlabroot/simulink/src/mixedm.c,isanexampleofahybrid (
Introduction1-5blocks with no states, x is an empty vector. In MEX-file S-functions, there aretwo separate state vectors for the continuous and discre
3 Writing S-Functions As C-MEX files3-66matlabroot/simulink/src/mixedm.c/* File : mixedm.c * Abstract: * * An example C MEX S-function that
Examples of C MEX-File S-Function Blocks3-67 /* Take care when specifying exception free code - see sfuntmpl.doc. */ ssSetOptions(S, SS_OPTION_E
3 Writing S-Functions As C-MEX files3-68 real_T *xD = ssGetRealDiscStates(S); real_T *xC = ssGetContStates(S); /* xD=xC */ if (ssIsSampleH
Examples of C MEX-File S-Function Blocks3-69during the simulation. In the transfer function used in this example, theparameters of the transfer functi
3 Writing S-Functions As C-MEX files3-70matlabroot/simulink/src/vsfunc.c/* File : vsfunc.c * Abstract: * * Example C-file S-function for def
Examples of C MEX-File S-Function Blocks3-71 ssSetNumSampleTimes(S, 1); ssSetNumRWork(S, 0); ssSetNumIWork(S, 0); ssSetNumPWork(S, 0);
3 Writing S-Functions As C-MEX files3-72/* Function: mdlOutputs ======================================================= * Abstract: * y = x */sta
Examples of C MEX-File S-Function Blocks3-73Example - Zero Crossing S-FunctionThe example S-function, sfun_zc_sat demonstrates how to implement asatur
3 Writing S-Functions As C-MEX files3-74/*========================* * General Defines/macros * *========================*//* index to Upper Limit */#d
Examples of C MEX-File S-Function Blocks3-75if ( ( numUpperLimit != 1 ) && ( numLowerLimit != 1 ) &&
1 Overview of S-Functions1-6Figure 1-2: How Simulink Performs SimulationInitialize m odelAt termina tion perf ormany required tasks.Calculate time of
3 Writing S-Functions As C-MEX files3-76 /* * states */ ssSetNumContStates(S, 0); ssSetNumDiscStates(S, 0); /* * outputs *
Examples of C MEX-File S-Function Blocks3-77/* * Modes and zero crossings: * If we have a variable step solver and this block has a continuous
3 Writing S-Functions As C-MEX files3-78#define MDL_SET_WORK_WIDTHS#if defined(MDL_SET_WORK_WIDTHS) && defined(MATLAB_MEX_FILE)/* Function
Examples of C MEX-File S-Function Blocks3-79 * and having a continuous sample time. Solvers work best on smooth problems. * In order for the solver
3 Writing S-Functions As C-MEX files3-80 for (iOutput = 0; iOutput < numOutput; iOutput++) { if (*uPtrs[uIdx] >= *upperLimit)
Examples of C MEX-File S-Function Blocks3-81 upperLimit += upperLimitInc; lowerLimit += lowerLimitInc; }
3 Writing S-Functions As C-MEX files3-82#define MDL_ZERO_CROSSINGS#if defined(MDL_ZERO_CROSSINGS) && (defined(MATLAB_MEX_FILE) || defined(
Examples of C MEX-File S-Function Blocks3-83static void mdlZeroCrossings(SimStruct *S){ int_T iOutput; int_T numOutput =
3 Writing S-Functions As C-MEX files3-84 }}#endif /* end mdlZeroCrossings *//* Function: mdlTerminate =============================================
Examples of C MEX-File S-Function Blocks3-85matlabroot/simulink/src/stvctf.c/* * File : stvctf.c * Abstract: * Time Varying Continuous Transfer F
Introduction1-7Simulink makes repeated calls to S-functions in your model. During thesecalls, Simulink calls S-function routines (also called methods)
3 Writing S-Functions As C-MEX files3-86 */#define S_FUNCTION_NAME stvctf#define S_FUNCTION_LEVEL 2#include "simstruc.h"/* * Defines for ea
Examples of C MEX-File S-Function Blocks3-87 "the numerator, nonempty and with first " &
3 Writing S-Functions As C-MEX files3-88 * NumBank1Coeffs * DenBank1Co
Examples of C MEX-File S-Function Blocks3-89 ssSetOffsetTime(S, 0, 0.0); /* * the second, discrete sample time, is user provided */ s
3 Writing S-Functions As C-MEX files3-90 } } /* * Normalize if this transfer function has direct feedthrough. */ for (i = 1; i
Examples of C MEX-File S-Function Blocks3-91 /* * The continuous system is evaluated using a controllable state space * represe
3 Writing S-Functions As C-MEX files3-92 if (den0 == 0.0) { den0 = mxGetPr(DEN(S))[0]; } /* * Grab the numerat
Examples of C MEX-File S-Function Blocks3-93 * Normalize if this transfer function has direct feedthrough. */ num = ssGetRWork(
3 Writing S-Functions As C-MEX files3-94 */ dx[0] = -den[1] * x[0] + *uPtrs[0]; for (i = 1; i < nContStates; i++) { dx[i] = x[i-1]
Function-Call Subsystems3-95Function-Call SubsystemsYou ca n create a triggered subsystem whose execution is determined by logicinternal to an S-funct
1 Overview of S-Functions1-8calls the appropriate functions for each flag value. For a C MEX S-function,Simulink calls the S-function routines directl
3 Writing S-Functions As C-MEX files3-96To configure an S-function to call a function-call subsystem:1 Specify which elements are to execute the funct
The C MEX S-Function SimStruct3-97The C MEX S-Function SimStructThe file matlabroot/simulink/include/simstruc.h is a C language headerfile that define
3 Writing S-Functions As C-MEX files3-98ssGetParentSS(S)This is typically not used in S-functions. It returns the parentSimStruct or NULL if the S is
The C MEX S-Function SimStruct3-99ssSetOptions(S,options)Used in mdlInitializeSizes t o set any of the following options.These options must be joined
3 Writing S-Functions As C-MEX files3-100ssSetOptions(S,options)(continued)SS_OPTION_ASYNCHRONOUS — This option applies onlyto S-functionsthat have 0
The C MEX S-Function SimStruct3-101Table 3-6: Error Handling and Status SimStruct MacrosMacros DescriptionssSetErrorStatus(S,"string")For i
3 Writing S-Functions As C-MEX files3-102Table 3-7: Input and Output Port Signal SimStruct MacrosMacro DescriptionssSetNumInputPorts(S,nInputPorts)Us
The C MEX S-Function SimStruct3-103ssSetInputPortOffsetTime(S,inputPortIdx,offset)Used in mdlInitializeSizes (a fterssSetNumInputPorts)tospecifythesam
3 Writing S-Functions As C-MEX files3-104ssSetInputPortReusable(S,inputPortIdx,value)Used in mdlInitializeSizes (afterssSetNumInputPorts) to specify w
The C MEX S-Function SimStruct3-105ssSetInputPortReusable(S,inputPortIdx,value)(continued)Note that this is a suggestion and not a requirement forthe
Introduction1-9S-Function ConceptsUnderstanding these key concepts should enable you to build S-functionscorrectly:• Direct feedthrough• Dynamica lly
3 Writing S-Functions As C-MEX files3-106ssSetOutputPortReusable(S,outputPortIdx,value)Used in mdlInitializeSizes (afterssSetNumOutputPorts) to specif
The C MEX S-Function SimStruct3-107ssGetInputPortRealSignalPtrs(S,inputPortIdx)Canbeusedinanysimulationloop(seep.3-16)S-function routine to access an
3 Writing S-Functions As C-MEX files3-108ssGetInputPortBufferDstPort(S,inputPortIdx)Can be used in any run-time (see p. 3-14) S-functionroutine to det
The C MEX S-Function SimStruct3-109ssGetOutputPortOffsetTime(S,outputPortIdx)Canbeusedinanyroutine(exceptmdlInitializeSizes)to determine the offset ti
3 Writing S-Functions As C-MEX files3-110ssGetSFcnParam(S,index)Used in any routine to access a parameter entered by in theS-function block dialog box
The C MEX S-Function SimStruct3-111ssIsSampleHit(S,st_index,tid)Used in mdlOutputs or mdlUpdate when your S-function hasmultiple sample t imes to dete
3 Writing S-Functions As C-MEX files3-112Table 3-10: State and Work Vector SimStruct MacrosMacro DescriptionssSetNumContStates(S,nContStates) Used in
The C MEX S-Function SimStruct3-113ssSetNumPWork(S,nPWork)Used in mdlInitializeSizes to specify the number of pointer(void *) work v ector elements as
3 Writing S-Functions As C-MEX files3-114ssGetNumDiscStates(S)Canbeusedinanyroutine(exceptmdlInitializeSizes)todetermine the number of discrete states
The C MEX S-Function SimStruct3-115ssGetPWork(S)Can be used in the simulation loop, mdlInitializeConditions,ormdlStart routines to get the pointer (vo
1 Overview of S-Functions1-10width can also be used to determine the number of continuous states, thenumber of discrete states, and the number of outp
3 Writing S-Functions As C-MEX files3-116Table 3-11: Simulation Information SimStruct MacrosMacro DescriptionssGetT(S)Used in mdlOutputs and mdlUpdat
The C MEX S-Function SimStruct3-117Table 3-12: Function-Call SimStruct MacrosMacro DescriptionssSetCallSystemOutput(S,index)Used in mdlInitializeSamp
3 Writing S-Functions As C-MEX files3-118Converting Level 1 C MEX S-Functions to Level 2Level 2 S-functions were introduced with Simulink 2.2. Level 1
Converting Level 1 C MEX S-Functions to Level 23-119• If your S -function has a nonempty mdlInitializeConditions, then updateit to the following form#
3 Writing S-Functions As C-MEX files3-120• If your S-function has a nonempty mdlUpdate, then update it to this form:#define MDL_UPDATEstatic void mdlU
Converting Level 1 C MEX S-Functions to Level 23-121Table 3-13: Obsolete SimStruct MacrosObsolete Macro Replace WithssGetU(S), ssGetUPtrs(S) ssGetInp
3 Writing S-Functions As C-MEX files3-122ssGetNumOutputs ssGetNumOutputPorts(S) andssGetOutputPortWidth(S,port)ssSetNumOutputs ssSetNumOutputPorts(S,n
4Guidelines for WritingC MEX S-FunctionsIntroduction ...4-2Classes of Problems Solved by S-Functions . . . . . . . . 4-2TypesofS-Func
4 Guidelines for Writing C MEX S-Functions4-2IntroductionThis chapter describes how to create S-functions that work seamlessly withboth Simulink and t
Introduction4-3environment with a great deal of flexibility. This flexibility cannot always bemaintained when you use S-functions with the Real-Time W
Introduction1-11• Continuous sample time — For S -functions that have continuous states and/ornonsampled zerocrossings.Fort his typeof S-function,theo
4 Guidelines for Writing C MEX S-Functions4-4The MathWorks has a dopted terminology for these different requirements.Respectively, the situations desc
Introduction4-5Fully Inlined S-FunctionsA fully inlined S-function builds your algorithm (block) into Simulink and theReal-Time Workshop in a manner t
4 Guidelines for Writing C MEX S-Functions4-6files),it embedssomeo f thisoverhead code inthe generatedC code.Ifyou wantto optimize your real-time code
Noninlined S-Functions4-7Noninlined S-FunctionsNoninlined S-functions are identified by the absence of an sfunction.tlc fileforyourS-function(sfunctio
4 Guidelines for Writing C MEX S-Functions4-8Writing Wrapper S-FunctionsThis section describes how to create S-functions that work seaml essly withSim
Writing Wrapper S-Functions4-9Wrapper S-functions are useful when creating new algorithms that areprocedural in nature or when integrating legacy code
4 Guidelines for Writing C MEX S-Functions4-10This figure i llustrates the wrapper S-function concept:Figure 4-1: How S-Functions Interface with Hand
Writing Wrapper S-Functions4-11Using an S-function wrapper to import algorithms in your Simulink modelmeans that the S-function serves as an interface
4 Guidelines for Writing C MEX S-Functions4-12/* * mdlInitializeSampleTimes - indicate that this S-function runs*at the rate of the source (driving bl
Writing Wrapper S-Functions4-13The TLC S-Function WrapperThis section describes how to inline the call to my_alg in the MdlOutputssection of the gener
1 Overview of S-Functions1-12S-functions can be either single or multirate; a multirate S-function hasmultiple sample times.Sample times are specified
4 Guidelines for Writing C MEX S-Functions4-14 /* Level2 S-Function Block: <Root>/S-Function (wrapsfcn) */ { SimStruct *rts = ssGetSFunction
Writing Wrapper S-Functions4-15to your C algorithm (my_alg), you can elim inate bo th the SimStruct and theextra function call, thereby improving the
4 Guidelines for Writing C MEX S-Functions4-16placing calls toyourS-function in the generatedcode. This is the wrapsfcn.tlcfile that inlines wrapsfcn.
Writing Wrapper S-Functions4-17The final step is the actual inlining of the call to the function my_alg.Thisisdone by theOutputs function. In this fun
4 Guidelines for Writing C MEX S-Functions4-18Fully Inlined S-FunctionsContinuing the example of the previous section, you could eliminate the ca ll t
Fully Inlined S-Functions4-19thatcontains multiple ports.You may findthat lookingat this example willaidin the understanding of fully inlined TLC file
4 Guidelines for Writing C MEX S-Functions4-20Fully Inlined S-Function with the mdlRTW RoutineYou can make a more fully inlined S-function that uses t
Fully Inlined S-Function with the mdlRTW Routine4-21• How to use the mdlRTW routine to customize the Real-Time Workshopgenerated code to produce the o
4 Guidelines for Writing C MEX S-Functions4-22The following graph illustrates how the parameters XData=[1:6],YData=[1,2,7,4,5,9] are handled. For exam
Fully Inlined S-Function with the mdlRTW Routine4-23index in the XData for the current x input value when the XData is unevenlyspaced. TheGetDirectLoo
Introduction1-13• A discrete S-function that changes at a specified ra te should register thediscrete sample time pair,[discrete_sample_time_period, o
4 Guidelines for Writing C MEX S-Functions4-24mxGetPr MATLAB API function. This results in a slight increase inperformance.mdlRTW UsageThe Real-Time W
Fully Inlined S-Function with the mdlRTW Routine4-25When creating this model, you need to specify the following for each S-functionblock:set_param(‘sf
4 Guidelines for Writing C MEX S-Functions4-26 rtY.Out1 = rtb_buffer2; /* S-Function Block: <Root>/S-Function1 */ { real_T *xData = &r
Fully Inlined S-Function with the mdlRTW Routine4-27matlabroot/simulink/src/sfun_directlook.c/* * File : sfun_directlook.c * Abstract: * * Di
4 Guidelines for Writing C MEX S-Functions4-28/*==============* * misc defines * *==============*/#if !defined(TRUE)#define TRUE 1#endif#if !defined(
Fully Inlined S-Function with the mdlRTW Routine4-29 } return(TRUE); } else { return(FALSE); }}/* end IsRealVect
4 Guidelines for Writing C MEX S-Functions4-30 /* * Verify we have a valid XDataEvenlySpaced parameter. */ if (!mxIsNumeric(XDATAEVENLYS
Fully Inlined S-Function with the mdlRTW Routine4-31 } else { /* XData is ‘unevenly-spaced’ */ for (i = 1; i < numEl; i++) {
4 Guidelines for Writing C MEX S-Functions4-32 ssSetInputPortOverWritable(S, 0, TRUE); if (!ssSetNumOutputPorts(S, 1)) return; ssSetOutputPor
Fully Inlined S-Function with the mdlRTW Routine4-33 cache->evenlySpaced = FALSE; }}#endif /* MDL_START *//* Function: mdlOutputs ======
How to Contact The MathWorks:508-647-7000 Phone508-647-7001 FaxThe MathWorks, Inc. Mail24 Prime Park WayNatick, MA 01760-1500http://www.mathworks.com
1 Overview of S-Functions1-14The simulink/blocks directory contains many M-file S-functions. Considerstarting off by looking at these files.Table 1-2:
4 Guidelines for Writing C MEX S-Functions4-34} /* end mdlOutputs *//* Function: mdlTerminate ====================================================== *
Fully Inlined S-Function with the mdlRTW Routine4-35 boolean_T even = (mxGetScalar(XDATAEVENLYSPACED(S)) != 0.0); if (!ssWriteRTWParamSe
4 Guidelines for Writing C MEX S-Functions4-36matlabroot/simulink/src/lookup_index.c/* File : lookup_index.c * Abstract: * * Contains a routine
Fully Inlined S-Function with the mdlRTW Routine4-37 */ for (;;) { idx = (bottom + top)/2; if (u < x[idx]) { top =
4 Guidelines for Writing C MEX S-Functions4-38matlabroot/toolbox/simulink/blocks/sfun_directlook.tlc%% File : sfun_directlook.tlc%% Abstract: %%
Fully Inlined S-Function with the mdlRTW Routine4-39%function Outputs(block, system) Output /* %<Type> Block: %<Name> */ { %assign
4 Guidelines for Writing C MEX S-Functions4-40 %endif %endroll %endif }%endfunction%% EOF: sfun_directlook.tlc
I-1IndexAadditional pa rameters for S-functions 2-20Bblock width 3-33block-based sample times 3-36CC MEX S-function routines 3-3C MEX S-functions 1-2,
IndexI-2mdlSetOutputPortSampleTime 3-34, 3-41mdlSetOutputPortWidth function 3-35mdlSetWorkWidths 3-46mdlStart 3-48mdlUpdate 3-42, 3-51memory and work
IndexI-3error handling and status 3-101function call 3-117general 3-97input a nd output port signal 3-102parameter 3-109sample time 3-110simulation in
Introduction1-15The simulink/src directoryalsocontainsexamplesofCMEXS-functions,many of which have an M-file S-function counterpart. These C MEXS-func
IndexI-4ssSetNumSampleTimes 3-110ssSetNumSFcnParams 3-109ssSetOffsetTime 3-110ssSetOptions 3-99ssSetOutputPortOffsetTime 3-105ssSetOutputPortReusable
1 Overview of S-Functions1-16mixedmex.cImplements a hybrid dynamical system with asingle output and two inputs.quantize.cAn example MEX-file for a vec
Introduction1-17simomex.cImplements a single output, two input state-spacedynamical system described by these state-spaceequationsdx/dt = Ax + Buy = C
1 Overview of S-Functions1-18
2Writing S-FunctionsAs M-FilesIntroduction ...2-2Defining S-Function Block Characteristics . . . . . . . . 2-3ASimpleM-FileS-Function
2 Writing S-Functions As M-Files2-2IntroductionAn M-file that definesan S-Function blockmust provide informationabout themodel; Simulink needs this in
Introduction2-3Building S-functions can be thought of as two separate tasks:• Initializingblockcharacteristics,includingnumber ofinputs,outputs,initia
2 Writing S-Functions As M-Files2-4A Simple M-File S-Function ExampleThe easiest way to understand how S-functions work is to look at a simpleexample.
Introduction2-5The first four input arguments, which Simul ink passes to the S-function,mustbe the variablest, x, u,andflag:• t, the time•x, the state
iContents1Overview of S-F unctionsIntroduction ... 1-2WhatIsanS-Function?... 1-2Whe
2 Writing S-Functions As M-Files2-6Below are the S-function subroutines that timestwo.m calls:%=======================================================
Introduction2-7To test this S-function in Simulink, connect a sine wave generator t o the inputof an S-Function block. Connect the output of the S-Fun
2 Writing S-Functions As M-Files2-8Examples of M-File S-FunctionsThe simple example discussed above (timestwo) has no states. MostS-Function blocks re
Examples of M-File S-Functions2-9Example - Continuous State S-FunctionSimulink includes a function called csfunc.m, which is an example of acontinuous
2 Writing S-Functions As M-Files2-10%==============================================================% mdlInitializeSizes% Return the sizes, initial con
Examples of M-File S-Functions2-11% End of mdlDerivatives.%%==============================================================% mdlOutputs% Return the blo
2 Writing S-Functions As M-Files2-12function [sys,x0,str,ts] = dsfunc(t,x,u,flag)% An example M-file S-function for defining a discrete system.% This
Examples of M-File S-Functions2-13% Call simsizes for a sizes structure, fill it in, and convert it % to a sizes array.sizes = simsizes;sizes.NumContS
2 Writing S-Functions As M-Files2-14Example - Hybrid System S-FunctionsSimulink includes a function called mixedm.m, which is an example of a hybridsy
Examples of M-File S-Functions2-15Here is the code for the M-file S-function:function [sys,x0,str,ts] = mixedm(t,x,u,flag)% A hybrid system example th
ii Contents3Writing S-Functions As C-MEX filesIntroduction ... 3-2Writing Basic C M EX S-Functions ...
2 Writing S-Functions As M-Files2-16sizes.NumOutputs = 1;sizes.NumInputs = 1;sizes.DirFeedthrough = 0;sizes.NumSampleTimes = 2;sys = simsizes
Examples of M-File S-Functions2-17% End of mdlUpdate.%%==============================================================% mdlOutputs% Return the output v
2 Writing S-Functions As M-Files2-18function [sys,x0,str,ts] = vsfunc(t,x,u,flag)% This example S-function illustrates how to create a variable % step
Examples of M-File S-Functions2-19sizes = simsizes;sizes.NumContStates = 0;sizes.NumDiscStates = 1;sizes.NumOutputs = 1;sizes.NumInputs = 2
2 Writing S-Functions As M-Files2-20function sys = mdlOutputs(t,x,u)sys = x(1);% end mdlOutputs%%=====================================================
3Writing S-FunctionsAs C-MEX filesIntroduction ...3-2Writing Basic C MEX S-Functions ...3-4Creating More Comp lex C MEX S-Func
3 Writing S-Functions As C-MEX files3-2IntroductionA C MEX-file that definesan S-Function block must provide information aboutthe model to Simulink du
Introduction3-3contents. After Simulink calls mdlInitializeSizes, i t t hen interacts with theS-function through various other routines (all starting
3 Writing S-Functions As C-MEX files3-4Writing Basic C MEX S-FunctionsThis secti on d iscusses bas ic C MEX S-f unctions, where basic means anS-functi
Writing Basic C MEX S-Functions3-5To incorporate this S-function into Simulink, create a source f ile calledtimestwo.c and place the S-function routin
iiiFunction-Call Subsystems ... 3-95The C MEX S-Function SimStruct ... 3-97Converting Level 1 C MEX S-Funct
3 Writing S-Functions As C-MEX files3-6mdlOutputsCalculation of outputs. For our timestwoS-function, mdlOutputs takes the input,multiplies it by two,
Writing Basic C MEX S-Functions3-7The contents of timestwo.c are shown below.#define S_FUNCTION_NAME timestwo#define S_FUNCTION_LEVEL 2#include “sims
3 Writing S-Functions As C-MEX files3-8There is more information that the timestwo.c example requires:• Defines and includes — The example specifies t
Writing Basic C MEX S-Functions3-9• mdlOutput:- The numerical calculation.mdlOutputs tells S imulink to multiply theinput signal by 2.0 and place the
3 Writing S-Functions As C-MEX files3-10Creating More Complex C MEX S-FunctionsThere are numerous S-function routines available for use in C MEXS-func
Creating More Complex C MEX S-Functions3-11The following headers are included by matlabroot/simulink/include/simstruc.hwhen compiling as a MEX-file.Wh
3 Writing S-Functions As C-MEX files3-12• simulink.c is included if the file is being compiled int o a MEX-file.•cg_sfun.h is included if the file is
Creating More Complex C MEX S-Functions3-13Note that the second argument to ssSetErrorStatus must be persistentmemory. It cannot be a local variable i
3 Writing S-Functions As C-MEX files3-14your S-function generates an exception when this option is set, unpredictableresults will occur.Allmex* routin
Overview of the C MEX S-Function Routines3-15Overview of the C MEX S-Function RoutinesThe following figure shows the calling structure, including opti
iv Contents
3 Writing S-Functions As C-MEX files3-16Figure 3-1: The Calling Sequence for S-FunctionsInitializationmdlSetInputPortWidth/mdlSetOutputPortWidthmdlIn
Overview of the C MEX S-Function Routines3-17The following sections discuss each of these routines and give an overview ofthemorecommonmacrosusedtoacc
3 Writing S-Functions As C-MEX files3-18Alternate Calling Structure for External ModeWhen running Simulink in external mode, the calling sequence for
Overview of the C MEX S-Function Routines3-19Data View of S-FunctionsS-function blocks have input and output signals, parameters, internal states,plus
3 Writing S-Functions As C-MEX files3-20The length of the various signals and vectors is configured in themdlInitializeSizes routine. The signals as w
Overview of the C MEX S-Function Routines3-21Accessing Input Signals of Individual PortsThis section describes how to access all input signals of a pa
3 Writing S-Functions As C-MEX files3-22entering your S-function. Then the driving source should be connected to eachinputportasshowninthisfigure:Chec
Overview of the C MEX S-Function Routines3-23and NUM_OF_CHANNELS_PRM. The code uses #define statements to associateparticular input arguments with the
3 Writing S-Functions As C-MEX files3-24Typically, it is safe to have an mdlCheckParameters in your S-function when itis used with the Real-Time Works
Overview of the C MEX S-Function Routines3-25Note You cannot access the w ork, state, input, output, and other vectors inthis routine. Use this rou t
1Overview ofS-FunctionsIntroduction ...1-2WhatIsanS-Function?...1-2WhentoUseanS-Function ...1-4HowS-Functions
3 Writing S-Functions As C-MEX files3-26mdlProcessParametersmdlProcessParameters is an optiona l routine that Simulink calls aftermdlCheckParameters c
Overview of the C MEX S-Function Routines3-27Example: mdlProcessParameters. This example processes a string parameter thatmdlCheckParameters has verif
3 Writing S-Functions As C-MEX files3-28mdlInitializeSizes function. Supplied ma cros set values for the structurefields. If a value is not specified,
Overview of the C MEX S-Function Routines3-29simulation(or theReal-TimeWorkshopexternalmode)ifan attempt ismadeto change the parameter.• If your S- fu
3 Writing S-Functions As C-MEX files3-30The synopsis is/* Function: mdlInitializeSizes ===============================================* Abstract:*
Overview of the C MEX S-Function Routines3-31 * of the output port which can be DYNAMICALLY_SIZE or greater than zero. */ if (!ssSetNumOutp
3 Writing S-Functions As C-MEX files3-32 * the size specified by the port which is usually referred to as * the block width. * * S
Overview of the C MEX S-Function Routines3-33either 1 or N.YoucanusessGetInputPortWidth in the routines called duringthe simulation loop to determine
3 Writing S-Functions As C-MEX files3-34When inherited port based sample times are specified, the sample time will beone of the following:• continuous
Overview of the C MEX S-Function Routines3-35This is the code synopsis for mdSetOutputPortSampleTime:#if defined(MDL_SET_OUTPUT_PORT_SAMPLE_TIME) &
1 Overview of S-Functions1-2IntroductionS-functions (system-functions) provide a powerful mechanism for extendingthecapabilitiesofSimulink®.Theintrodu
3 Writing S-Functions As C-MEX files3-36Setting Sample Times for C MEX S-FunctionsSimulink supports blocks that execute at different rates. There are
Overview of the C MEX S-Function Routines3-37Specifying the Number of Sample Times in mdlInitializeSizes. To configure yourS-function block for block-
3 Writing S-Functions As C-MEX files3-38Alternatively, you can specify that the sample time is in herited from thedriving block in which case the S-fu
Overview of the C MEX S-Function Routines3-39To check for a sample hit during execution (in mdlOutputs or mdlUpdate), usethessIsSampleHit or ssIsConti
3 Writing S-Functions As C-MEX files3-40Specifying the Number of Sample Times in mdlInitializeSizes. To specify port-basedsample times, usessSetNumSam
Overview of the C MEX S-Function Routines3-41Constant, triggered, and variable step sample times will not be propagated toS-functions with port based
3 Writing S-Functions As C-MEX files3-42Multirate S-Function BlocksIna multirate S-Function block, you canencapsulate the code that defines eachbehavi
Overview of the C MEX S-Function Routines3-43Example - Defining a Sample Time for a Hybrid Block. This examp le defines sampletimes for a hybrid S-Fun
3 Writing S-Functions As C-MEX files3-44Work vectors have several advantages:• Instance specific storage for block variables• Integer, real, pointer,
Overview of the C MEX S-Function Routines3-45Specify vector widths in mdlInitializeSizes. There are three choices:• 0 (the default). This indicates th
Introduction1-3Figure 1-1: The Relationship Between an S-Function Block, Its Dialog Box,and the Source File That Defines the Block’s BehaviorIn this
3 Writing S-Functions As C-MEX files3-46the mdlZeroCrossings routine to return the nonsampled zero crossings. Seematlabroot/simulink/src/sfun_zc.c for
Overview of the C MEX S-Function Routines3-47This code retrieves the FILE pointer from the pointer-work vector and passes ittofclose to close the file
3 Writing S-Functions As C-MEX files3-48routines. In mdlStart allocate and initialize the memory and place the pointerto it either in pointer-work vec
Overview of the C MEX S-Function Routines3-49Simulink will call this routine in two places:• At the start of simulation• If it is present in an enable
3 Writing S-Functions As C-MEX files3-50S-Function Routines Called During SimulationConceptually, the way Simulink performs a simulation is that it ex
Overview of the C MEX S-Function Routines3-51For an example of an mdlOutputs routine that works with mult iple input andoutput ports, seematlabroot/si
3 Writing S-Functions As C-MEX files3-52last call to this routine. The memory allocated to the derivative vector changesduring execution.The synopsis
Overview of the C MEX S-Function Routines3-53mdlTerminateIn the mdlTerminate routine, perform any actions that are necessary at thetermination of a si
3 Writing S-Functions As C-MEX files3-54The parameter can also be a variable as inmodules = 'sfun_module1 sfun_module2'set_param(sfun_block,
Overview of the C MEX S-Function Routines3-55routineoryourS-functionhas a“simulationmode”and a “real-timemode”suchas a hardware I/O S-function that si
Commentaires sur ces manuels