execute part of script only if script is called with a callback in simulink

6 visualizaciones (últimos 30 días)
Jakob
Jakob el 27 de Nov. de 2020
Editada: Gayathri el 5 de Jun. de 2025
Hello,
I have a MATLAB script which I use as a callback in simulink with run('myScript.m')
Sometimes I need to execute the script outside of simulink with slightly different behaviour. Is it possible to execute part of my code just if its called in simulink with the callback and the other way around just if I run the script in matlab?
Thanks for your help

Respuestas (1)

Gayathri
Gayathri el 5 de Jun. de 2025
Editada: Gayathri el 5 de Jun. de 2025
Hi @Jakob,
I get that you have to execute two different behaviours inside and outside of Simulink. For that you can use the "bdIsLoaded" function to determine whether model, subsystem, or library is loaded. So including this function in the script would allow us to define different behaviours in the script. Please refer to the code below to implement the same.
% myScript.m
% Check if running in Simulink
inSimulink = false;
try
% Check if a Simulink model is loaded and active
if bdIsLoaded(bdroot)
inSimulink = true;
end
catch
% If bdroot fails, we're likely not in Simulink
inSimulink = false;
end
% Code to run only in Simulink
if inSimulink
disp('Running in Simulink callback!');
% Simulink-specific behavior
% Example: Access Simulink model parameters
modelName = bdroot;
paramValue = get_param(modelName, 'SimulationTime');
end
% Code to run only in MATLAB
if ~inSimulink
disp('Running directly in MATLAB!');
% MATLAB-specific behavior
% Example: Use command-line inputs or different logic
userInput = input('Enter a value: ');
disp(['You entered: ' num2str(userInput)]);
end
Please make sure that all the Simulink models are closed when you run the script in MATLAB otherwise the "inSimulink" variable would be initialized to "true".
You can implement your functionality inside respective "if" blocks.
Refer to the below link for more information about the "bdIsLoaded" function.
I hope this helps!

Categorías

Más información sobre Model, Block, and Port Callbacks en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by