Main Content


Initialize the state vectors of this MATLAB S-function









Instance of Simulink.MSFcnRunTimeBlock class representing the Level-2 MATLAB S-Function block.


The Simulink® engine invokes this optional method at the beginning of a simulation. It should initialize the continuous and discrete states, if any, of this S-Function block. In a Level-2 MATLAB S-function, use the ContStates or Dwork run-time object methods to access the continuous and discrete states. This method can also perform any other initialization activities that this S-function requires.


If you have Simulink Coder™, and you need to ensure that the initialization code in the InitializeConditions function is run only once, then move this initialization code into the Start method. MathWorks® recommends this code change as a best practice.

If this S-function resides in an enabled subsystem configured to reset states, the Simulink engine also calls this method when the enabled subsystem restarts execution.

The Simulink engine calls InitializeConditions prior to calculating the S-function's input signals. Therefore, since the input signal values are not yet available, InitializeConditions should not use the input signal values to set initial conditions. If your S-function needs to initialize internal values using the block's input signals, perform the initialization in Outputs.

For example, in a C MEX S-function, initializes an IWork vector with one element in the mdlInitializeSizes method.

ssSetNumIWork(S, 1);

The IWork vector holds a flag indicating if initial values have been specified. Initialize the flag's value in the mdlInitializeCondition method.

static void mdlInitializeConditions(SimStruct *S)
  /* The mdlInitializeConditions method is called when the simulation
     start and every time an enabled subsystem is re-enabled.
     Reset the IWork flag to 1 when values need to be reinitialized.*/

  ssSetIWorkValue(S, 0, 1);

Check the value of the IWork vector flag in the mdlOutputs method, to determine if initial values need to be set. Since the engine has calculated input values at this point in the simulation, the mdlOutputs method can use them to initialize internal values.

static void mdlOutputs(SimStruct *S, int_T tid)
    // Initialize values if the IWork vector flag is true. //
    if (ssGetIWorkValue(S, 0) == 1) {
             // Enter initialization code here //

    // Remainder of mdlOutputs function //

For a Level-2 MATLAB S-function, use a DWork vector instead of an IWork vector in the previous example.


This example initializes both a continuous and discrete state to 1.0. Level-2 MATLAB S-functions store discrete states in their DWork vectors.

function InitializeConditions(s)

s.ContStates.Data(1) = 1;
s.Dwork(1).Data      = 1;

% endfunction

Version History

Introduced in R2012b