Want to change Matlab current folder to be the same as Simulink
6 views (last 30 days)
Is there any way for Simulink (R2021b) to change the Matlab current folder to be the same as the .slx file? I've got a Simulink model that uses a Matlab System block. I have the Matlab .m code in the same directory as the .slx file. However, if I run my Simulink simulation without remembering to change the Matlab current folder, then I get the "System Not Found" error. Ideally I'd like to be able to run my Simulink simulation without having to worry about where the files are, as long as they're in the same directory. Any ideas?
Paul on 23 Dec 2021
The easiest thing to do is use addpath() once to add the location of the .slx file to the search path.
Alternatively, add this code to the model PreLoadFcn callback
And in the model CloseFcn callback
This approach will add the folder with .slx file to the path and keep it there until you close the model.
Slightly more complex approach that modifies the directory during Run or Update (which may be problematic, actually) and then reverts when the simulation stops.
In the model InitFcn callback use the following code:
current_dir = cd; % save for later
sim_dir = fileparts(get_param(bdroot,'FileName'));
Note: current_dir and sim_dir will be created in the base workspace. So use variable names that you know will not step on variables that already exist in the base workspace. Also current_dir will be used later (see below) and they both will be cleared when the simulation stops, so make sure you choose variable names that won't be overwritten by other simulaton outputs to the base workspace.
In the model StopFcn callback use the following code
clear current_dir sim_dir
I tried this with a simple model using the Run button and it seemed to work. However, be careful if using the model in question as a Model Reference. Also, there may be other gotchas if using the sim() command.