To change Current Folder to the folder of .m File

217 Ansichten (letzte 30 Tage)
Afz
Afz am 16 Apr. 2013
Kommentiert: Junho Kweon am 12 Jul. 2023
How can I change the current folder to folder of .m file in my code.
Possibly with cd command
Or any command I can indicate that my excel file is in same location as .m file.
e.g. code.m path folder\My excel file.xls

Antworten (4)

Image Analyst
Image Analyst am 17 Apr. 2013
Bearbeitet: Image Analyst am 17 Apr. 2013
Here's some code I got from Brett Shoelson of the Mathworks:
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
Edit: Note that the isdeployed is important if you will be compiling and deploying your application. This let's it operate both for you, as the developer, and for your deployed application where it will skip the cd because doing cd like that in a deployed app can wreak havoc. If you won't be doing compiling, then you can do just the cd without the if.
  3 Kommentare
Yannis Axaopoulos
Yannis Axaopoulos am 26 Nov. 2022
Bearbeitet: Yannis Axaopoulos am 27 Nov. 2022
This command that ran fine in my MATLAB R2015b, is not actually working in the newest R2022a!
EDIT:
Actually find the solution in an other answer
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(matlab.desktop.editor.getActiveFilename));
end
Junho Kweon
Junho Kweon am 12 Jul. 2023
I do not think this command properly work for when I use 'Run Section'..

Melden Sie sich an, um zu kommentieren.


Diaa
Diaa am 15 Mai 2021
For live scripts, @Qi Wang suggested using this:
fileparts(matlab.desktop.editor.getActiveFilename)
to get the full path of the active live script file.
  1 Kommentar
Javier Ros
Javier Ros am 4 Mär. 2022
This works, but the problem is that most people expects code in .m file to work in .mlx and viceversa.
I think that this issue should be adressed by MATLAB's guys.
Best regards,
Javier

Melden Sie sich an, um zu kommentieren.


Florian
Florian am 13 Jul. 2018
mfile_name = mfilename('fullpath');
[pathstr,name,ext] = fileparts(mfile_name);
cd(pathstr);

Matt Kindig
Matt Kindig am 17 Apr. 2013
cd(which(fileparts('/path/to/your/file.m')))

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by