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.
Pull off the file-name part. cd() to what remains. pwd() to find out the directory name. cd() back.
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) file=java.io.File(filename); if file.isAbsolute() fullpath = filename; else fullpath = char(file.getCanonicalPath()); end if file.exists() return else error('resolvePath:CannotResolve', 'Does not exist or failed to resolve absolute path for %s.', filename); end