execute part of script only if script is called with a callback in simulink
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Gayathri
2025-6-5
编辑:Gayathri
2025-6-5
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!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Model, Block, and Port Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!