MATLAB: Changing Simevent attribute using Matlab Function Block

matlab function block delaySimEvents

Hello,
Lets suppose I want to select an Output Switch's port based on the value of an entity's attribute. If Attr == 0 then port 1 is selected, else port 2. There are several ways to do it, but I chose to implement it as shown in the image bellow, using a Get Attribute block a Matlab Function block with a Server in parallel in order to add a delay until Matlab Function's output is calculated.
The Matlab function is the following:
function PortSel = fcn(Attr)
PortSel = (Attr > 0)+1;
My question is why does the Server need a delay of 1 instead of zero in order the system to work as expected?
What I am trying to understand is when the Matlab Function block's code is calculated in order to use it in other situations. For example the same question arises if instead of an output switch I used a Set Attribute Block as stated by Devdatt Lad in this thread.

Best Answer

The Server does not need a delay of 1 for this to work - it should work with a delay of 0. The reason for the extra Server is to hold the entity temporarily while we perform a computation that affects the entity's path (output switch). So a time delay is not required.
If you are not seeing the expected behavior then it could be an issue of event priorities. Here are the sequence of events that will happen above:
  • Entity arrives at Server, which will schedule a departure event for this entity for timeNow+0. This event will have an event priority as specified in the Server block.
  • The signal computations will then be executed. This includes the MATLAB Function block and hence a new value will be produced at the "p" port of the Output Switch.
  • The Output Switch will sense this change and schedule an update event for tNow to switch its selected port. This update event will be at the priority specified in the Output Switch block, if specified.
  • The system will then schedule the above two events (both for tNow) in the order of ascending event priorities.
So if you are seeing the entity leave from the wrong port, then it is likely that the Departure event has a higher priority than the PortSelection event. Try making the event priority parameter on the Output Switch to be a lower number (higher priority) than the event priority value on the Server. Or alternatively, turn off the checkbox "Resolve simultaneous signal updates using event priority".