Want to change Matlab current folder to be the same as Simulink

조회 수: 36 (최근 30일)
Glenn Kubota
Glenn Kubota 2021년 12월 22일
댓글: Glenn Kubota 2021년 12월 23일
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
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 CenterFile Exchange에서 Programmatic Model Editing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by