Change Subsystem Reference Component Dynamically Using
This example shows how to dynamically change the subsystem reference component using the Initialization Function.
InitFcn is used to change the implementation of the model without having to change the contents. This example model simulates the front and rear wipers of a vehicle. The front wiper is sensor-based and it senses rain and fog. The rear wiper is controlled by the driver.
Explore the Model
Inputs: The wipers are turned on during rain or fog. Double-click Turn on Fog Sensor or Turn on Rain Sensor component on the top left corner of the model to select the type of input. Based on the selection, the sensor input variable
SensorInput is created in the model workspace.
Wiper speed controller: During simulation the
InitFcn is executed and calls the
switchSensor function. This function reads the variable
SensorInput from the model workspace and changes the subsystem to
slexFogSensor according to your input selection. The subsystem reference component (Rain or Fog) converts the input voltage into speed levels low, medium, and high. The wiper speed controller converts the front and rear wiper speed levels into the appropriate speed in cycles per second.
Use this code in the
InitFcn call back
function wiperController(bd, option) switch option case 'PostLoad' createWiperConstants(bd); case 'Init' switchSensor(bd); otherwise end end
function switchSensor(bd) mws = get_param(bdroot, 'modelworkspace'); si = mws.getVariable('SensorInput'); blockpath = [bd '/SensorBasedSpeedController']; if strcmp(si,'Fog') set_param(blockpath,'ReferencedSubsystem','slexFogSensor'); elseif strcmp(si,'Rain') set_param(blockpath,'ReferencedSubsystem','slexRainSensor'); end end