Is it not possible to set script directory to current directory as default in MATLAB?
조회 수: 2 (최근 30일)
이전 댓글 표시
I dont want to always put this line in my scripts: cd(fileparts(which(mfilename)));
댓글 수: 2
KSSV
2017년 9월 8일
What's the necessity to keep? You keep all your files in one folder and run from the folder...
Stephen23
2017년 9월 8일
편집: Stephen23
2017년 9월 8일
"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.
답변 (1개)
Jan
2017년 10월 2일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!