Want to change Matlab current folder to be the same as Simulink
26 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Paul
2021-12-23
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
addpath(fileparts(get_param(bdroot,'FileName'));
And in the model CloseFcn callback
rmpath(fileparts(get_param(bdroot,'FileName'));
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'));
cd(sim_dir);
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
cd(current_dir);
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Programmatic Model Editing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!