Is it not possible to set script directory to current directory as default in MATLAB?
2 views (last 30 days)
Show older comments
I dont want to always put this line in my scripts: cd(fileparts(which(mfilename)));
2 Comments
KSSV
on 8 Sep 2017
What's the necessity to keep? You keep all your files in one folder and run from the folder...
Stephen23
on 8 Sep 2017
Edited: Stephen23
on 8 Sep 2017
"I dont want to always put this line in my scripts: cd(fileparts(which(mfilename)));"
It is good that you do not want to put that line is your code, because that line is a bad way to write code (slow, pointless, hard to debug, obfuscated):
- runtime introspection using mfilename is slow.
- runtime introspection using which is incredibly slow.
- using cd is slow, and makes debugging very difficult. Using cd is something that beginners do instead of learning how to specify filepaths properly.
You should simply:
- use functions rather than scripts, and
- use absolute/relative filepaths,
then you won't need any of those slow functions or that line of code. Fix the bad code design and your code will be simpler, more robust, more efficient, and easier to debug.
Answers (1)
Jan
on 2 Oct 2017
It is not clear, why you do this at all. Is the purpose to access other files in the same folder as the script without specifying the path? If so, this a very fragile. If you call another script, the current folder might change and the file access will occur in the wrong folder.
Prefer to store the data apart from the code. But if you really want to use the parent folder of the current file, use:
myPath = fileparts(mfilename('fullpath'));
Data = load(fullfile(myPath, 'TestData.mat'));
This is much faster than the slow which and cd commands, and it does not change the current folder. This avoids conflicts with other functions.
0 Comments
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!