One of my answers was recently downvoted for suggesting use of cd(path_to_toolbox
) rather than one of the path
tools, such as addpath
or rmpath
. Given the fervent criticism I received I must imagine that there are very good reasons for using the path
tools, presumably they are in some way more robust, especially when code is distributed to other systems.
Then I decided to clock the performance of cd
versus addpath
and was surprised to find the following result. Prior to each trial I cleared the workspace and created a string array with alternating paths:
clear
clc
p1 = 'c:\MATLAB7\toolbox\symbolic\@sym\';
p2 = matlabroot;
newpath = repmat(' ',100,100);
for ii=1:2:99
newpath(ii,1:length(p1)) = p1;
newpath(ii+1,1:length(p2)) = p2;
end
Then I ran either addpath
or cd
as follows:
tic
for ii=1:100
addpath(newpath(ii,:))
end
toc
Elapsed time is 13.437000 seconds.
tic
for ii=1:100
cd(newpath(ii,:))
end
toc
Elapsed time is 1.078000 seconds.
Any comments on whether there are conditions under which use of cd
might be justified, for instance to set the path to a function (toolbox or otherwise), are appreciated. While it may be considered sloppy, I have used cd
for many years and while the slowdown can be appreciable if used repeatedly, I find that if it is not used in highly iterated parts of a program the slowdown is worth the simplicity it brings to coding. Notably, addpath
is not more complicated to use, but now I seem to have a real reason to prefer cd
: it's actually faster.
Edit
As a postscript to this post I plead mea culpa to perverse use of cd
(and in this example, addpath
). There should however be room for such usage in what is a language that is frequently used for quick-and-dirty scripting. It should be kept in mind that there is a gradation of expertise among the users of matlab, and in some cases less "advanced" and seemingly sloppy programming techniques can in fact be construed as advantageous in the short term (if not the long term, or where version and directory structure management might become problematic).
As an appendix I include some links to posts on SO and beyond that address built-in function overriding, shadowing, and the like, where addpath
(and I would argue cd
too) can be used:
How to unhide an overriden function?
How to get a handle to an overriden built-in function?
How to wrap an already existing function with a new function of the same name
http://www.mathworks.in/matlabcentral/newsreader/view_thread/264354