MATLAB: Check referenced models do exist

find_mdlrefsfind_systemMATLABmodel referencesimulink

I have a model which contains multiple models referenced to it sequentially.
Eg. Main_model has 2 mdlrefs sub_mdl1 and sub_mdl2. sub_mdl1 has 4 mdlrefs and sub_mdl2 has 5 mdlrefs.
I'm trying to configure a setting in all the referenced model within Main_model.
The script seems to work correctly if all the ref models(within Main_model) do exist in the directory.
But suppose if one(sub_mdl1_num2) of the 4 models of sub_mdl1 is renamed or missing(for that matter), then the command
modelRefNames = find_mdlrefs('sub_mdl1', 'ReturnTopModelAsLastElement', false)
results in an error:
No system or file called 'sub_mdl1_num2' found.
Error in load_model
This made me think. As I'm dealing with a model which is dependent on other models(being generated at a later stage, assume Stage 2),
so running this script at Stage 1 will result in this error, due to unavailability of sub_mdl1_num2, which is meant to be generated at Stage 2.
Keeping a check if all the referenced models are present or not before the configuring a setting would be great.
So, this is where I'm stuck. Do we have any feature/function within find_mdlrefs, which can warn us before trying to load absent model ?
Or anything of this sort. I just want the existing and easiest way to do so,
because adding another maneuver to perform this prior check would mean another 5-6 seconds added to script execution.
Thanks in advance, umesh.

Best Answer

You can do this.
MdlRef=find_system(Model,'BlockType','ModelReference');
for k=1:length(MdlRef)
SubModel=get_param(MdlRef{k},'ModelFile');
if ~exist(SubModel,'file')
error([SubModel,' does not exist'])
end
end
To make this work for nested model reference, you need to make the above code a recursive function.
Keep in mind, the only way to find what's inside a model is to load or open the model. In the nested situation, if 'sub_mod1.slx' does not even exist, there is no way to know how many model references exist in 'sub_moe1'.