avoiding use of cd to resolve filenames

I am losing a lot of time in my code in a subfunction of the memmapfile constructor which resolves the pathname of the file in question. The code (copyright 2004-2006, The MathWorks, Inc.) has the following:
oldDir = cd(directory);
resolvedName = fullfile(cd(oldDir), [basename extension]);
A profile confirms this consumes an unacceptable amount of time (as compared to just calling resolvedName = fullfile(directory,[basename extension])
Does anybody have a workaround? I was thinking just calling the naive fullfile, then checking for existence of the file (via fopen, say), and falling back to the double cd code above.
BTW, this is from Matlab 2007a. Perhaps TMW has fixed this in newer releases...

 Accepted Answer

I would think that will be faster too. For checking the existence of the file, use exist(...,'file') must be faster than using fopen().
See this post for some encouragement, but again "swim at your own risk".

More Answers (1)

File = which('pathdef.m');
tic;
for i=1:1000
f=fopen(File, 'r');
ex=(f~=-1);
fclose(f);
end
toc % 0.12 sec
tic;
for i=1:1000
ex = exist(File, 'file');
end
toc % 0.17 sec
It seems that FOPEN is faster. In older versions FOPEN('r+') was much faster than FOPEN('r'), because the first considers a fullpath name, while the later searched the Matlab PATH even if the file contained a full path. But in Matlab 2009a FOPEN('r') is faster.
A small C-Mex file can test the existence of a file 10 times faster and the missing 20 times faster. Unfortunately I hesitate to publish it in the FEX due to problems with converting Unicode characters under Linux and MacOS (see: http://www.mathworks.com/matlabcentral/answers/3198-convert-matlab-string-to-wchar-in-c-mex-under-windows-and-linux)
FEX: GetFullPath may be helpful also to create a fully qualified path.

Tags

Community Treasure Hunt

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

Start Hunting!