MATLAB: How to access simulation data of multiple blocks in the same simulation using multiple event listeners

accessdataeventlistenersmultipleSimscapesimulation

I have a Simulink model set up with event listeners so that I can access the simulation data while it runs. To do this, I followed the instructions from this documentation link:
The issue is that I want to create multiple event listeners so that I can access the data of many blocks from the simulation, but I can't seem to figure out how to do this. I tried placing the following code in the "StartFcn" model callback, but it only created the last listener in the loop:
blockName=find_system(mdl);
for i=1:length (blockName)-1
blkRTO = get_param(blockName{i+1},'RuntimeObject');
h=add_exec_event_listener(blkRTO,'PostOutputs',@change_block_color);
end

Best Answer

To do this, you just need to create an array of event listeners. The issue with the above code is that the event listener "h" is overwritten each iteration of the loop. To fix this, you replace the "StartFcn" callback with the following code:
 
blks = find_system('myModel');
numBlks = length(blks)-1; %1st entry is model itself
for i=1:numBlks % Loop through all blocks in model
blkName =blks{i+1};
blkRTO = get_param(blkName,'RuntimeObject');
if ~isempty(blkRTO) % If block is virtual, RTO will be empty
  % Use array indexing so that event listeners are not overwritten
h(i)=add_exec_event_listener(blkRTO,'PostOutputs', @change_block_color);
else
disp(['No RTO object for ' blkName ', most likely because it is a virtual block']) % This message outputs to diagnostic viewer
end
end