Initialising a Simulink model workspace from MATLAB file - how to determine the parent model?

2 次查看(过去 30 天)
Hi everybody,
I've recently learnt how to make use of the Simulink model worksapce, to keep large numbers of parameters separate from the base workspace. Specifically, I am using a "MATLAB file" (Initialise.m) as the data source, which loads a lot of data used only by this model. However, I find myself interacting with this model in 2 different ways:
  1. When developing the model it is convenient to simply run Initialise.m from the command window, and open the model manually, allowing me to click the run button and interact immediately with the outputs. For this reason the model is always saved with the DataSource set to "model file", so it does not take ages to open.
  2. When using the model in anger it is run within a parfor loop using the sim command, allowing parameter sweeps to be performed. Within this parfor, the data source therefore gets set to Initialise.m, before reinitialising the model using the code below. Finally the model is closed without saving, so it can always be opened quickly, allowing it to be used in way above.
mdlWks.DataSource = 'MATLAB File';
mdlWks.FileName = 'Initialise.m';
mdlWks.reload
MY QUESTION IS within Initialise.m, is it possible to determine which of the 2 methods is being used? i.e. when that function is being run as part of a model initialisation? This will allow me to set some certain parameters in the correct way, either to some default values (for method 1), or based on the parameter sweeps (for method 2).
Many thanks for any help!
Lee

回答(1 个)

Vaibhav
Vaibhav 2023-12-29
编辑:Rena Berman 2024-7-16
Hi Lee
It is my understanding that you would like to determine whether "initialize.m" is being executed directly from the command window or as part of a Simulink model's initialization.
As "Initialize.m" is in the base workspace when run from the command window and in the model workspace when run as part of model initialization, a possible workaround is to use 'evalin' function to check the workspace context.
Here is an example code snippet:
function Initialise()
% Check the workspace context
if isempty(evalin('base', 'get_param(0, ''CurrentSystem'')'))
% Code specific to running from the command window
disp('Running from the command window.');
% Set default parameters or take actions for method 1
else
% Code specific to running as part of model initialization
disp('Running as part of model initialization.');
% Set parameters based on parameter sweeps or method 2
end
% Your common initialization code here
% Additional code...
disp('Initialization complete.');
end
You can refer to the following MathWorks documentation link to know more about "evalin" function:
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Programmatic Model Editing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by