MATLAB Answers


Fully resolving path names

Asked by Ray
on 12 Dec 2012

Objective: retrieve and store an absolute (or fully-qualified) path name for a file or directory from a user specified string which could be given as absolute, relative to a MATLAB path, relative to the current working directory ('.' or '..'), or relative to a user's directory (~ or ~user).

Builtin functions like EXIST and WHICH do a great job of searching out files that are on the path, hidden in class folders, specified as relative to the current directory, ... but they do not robustly return the full path for generic files (i.e. non-MATLAB user files that may not be on the MATLAB path). WHICH has a somewhat nonsensible behavior of claiming a file that EXIST, DIR, and FOPEN can find does not exist.

The goal is to be able to robustly obtain the absolute path name for a file so that it can be found again even from a different working directory or with a different MATLAB path.

For now my solution is to confirm existence of the file (EXIST) then save both the specified filename and the current working directory. Assuming that the MATLAB path doesn't change, I can cd to the directory, execute FOPEN, and then cd back whenever I need to access the file. Neither clean nor efficient.

Ideally I would like a function absolutePath = resolvePath(filename) that uses the same search criteria as the builtin functions.



Log in to comment.

3 Answers

Answer by Walter Roberson
on 12 Dec 2012

Pull off the file-name part. cd() to what remains. pwd() to find out the directory name. cd() back.

  1 Comment

Thanks for the input. Your suggestion does solve some of the issues. However, if the input string is relative to the current working directory, one of the MATLAB paths, or one of the other nooks and crannies that EXIST and other builtins check, your solution will fail because there is no where to CD.

Log in to comment.

Answer by Ray
on 12 Dec 2012

Not a complete solution for all the smart places the builtin's look, but a useful snippet that should work for most user file and directory applications:

function fullpath = resolvePath(filename);
  if file.isAbsolute()
      fullpath = filename;
      fullpath = char(file.getCanonicalPath());
  if file.exists()
      error('resolvePath:CannotResolve', 'Does not exist or failed to resolve absolute path for %s.', filename);


Log in to comment.

Answer by Jan Simon
on 12 Dec 2012


Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!