Is it not possible to set script directory to current directory as default in MATLAB?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I dont want to always put this line in my scripts: cd(fileparts(which(mfilename)));
2 Kommentare
KSSV
am 8 Sep. 2017
What's the necessity to keep? You keep all your files in one folder and run from the folder...
Stephen23
am 8 Sep. 2017
Bearbeitet: Stephen23
am 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.
Antworten (1)
Jan
am 2 Okt. 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 Kommentare
Siehe auch
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!