Reputation: 3135
I've noticed that most Matlab functions that acess files, e.g. load()
resolve relative paths by finding some directory on the current path that contains files or directories matching these paths. E.g. calling load('foo/bar.m')
will load /home/someuser/dir1/foo/bar.m
over /home/someuser/dir2/foo/bar
if the current working directory is /home/someuser/dir2
but /home/someuser/dir1
is on the search path.
I find this to be highly irritating and error-prone, how can I access files relative to the current working directory instead?
Upvotes: 0
Views: 1299
Reputation: 1116
As you know, Matlab can resolve both relative and absolute paths. But my suggestions to handle your issue with less headaches:
PATH.SCRIPT = fileparts(mfilename('fullpath'))
cd(PATH.SCRIPT)
load([PATH.SCRIPT, filesep, 'filename'])
or
load([PATH.SCRIPT, filesep, '..' , filesep, 'file_at_upper_dir_name'])
or
load([PATH.SCRIPT, filesep, 'subfolder' , filesep, 'file_at_lower_dir_name'])
If possible, try not messing too much with Matlab's default path, and at initialization of your workspace call restoredefaultpath
. This reduces chances that there is a spurious folder in your path where name collisions can happen.
As others have mentioned, ./
or ['.', filesep]
also provides with with the current folder.
As @CrisLuengo mentions, instead of filesep
one might prefer to compose paths with fullfile
, for instance: load(fullfile(PATH.SCRIPT, '..', 'file_at_upper_dir_name'))
Upvotes: 1