To change Current Folder to the folder of .m File

조회 수: 391(최근 30일)
Afz 2013년 4월 16일
댓글: Javier Ros 2022년 3월 4일
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


Image Analyst
Image Analyst 2013년 4월 17일
편집: Image Analyst 2013년 4월 17일
Here's some code I got from Brett Shoelson of the Mathworks:
% Change the current folder to the folder of this m-file.
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.
  댓글 수: 1
Diaa 2020년 4월 10일
편집: Diaa 2020년 4월 10일
If I have a live script on the MATLAB online drive inside some subfolder, what should I write to change the working directory to that of the live script since
doesn't work for live scripts on the online drive?
My workaround is to copy/paste your code inside an m-file in the same subfolder and call it at the very first line of my live script, however, I would like to have a neat solution.

댓글을 달려면 로그인하십시오.

Florian 2018년 7월 13일
mfile_name = mfilename('fullpath');
[pathstr,name,ext] = fileparts(mfile_name);

Diaa 2021년 5월 15일
For live scripts, @Qi Wang suggested using this:
to get the full path of the active live script file.
  댓글 수: 1
Javier Ros
Javier Ros 2022년 3월 4일
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,

댓글을 달려면 로그인하십시오.

Matt Kindig
Matt Kindig 2013년 4월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by