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 个评论
Stephen23
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
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.

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by