Peter
Peter

Reputation: 3135

Matlab: access files relative to working directory

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

Answers (1)

Mefitico
Mefitico

Reputation: 1116

As you know, Matlab can resolve both relative and absolute paths. But my suggestions to handle your issue with less headaches:

  1. At each (relevant/main) script ensure that your workspace is the scripts location with:

PATH.SCRIPT = fileparts(mfilename('fullpath')) cd(PATH.SCRIPT)

  1. Then, always call functions with absolute paths using:

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'])

  1. 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.

  2. As others have mentioned, ./ or ['.', filesep] also provides with with the current folder.

  3. 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

Related Questions