Mohammad Moghimi
Mohammad Moghimi

Reputation: 4686

Is there any downside for calling MATLAB's addpath many times?

My questions is if addpath is similar to #include in C. In C if you don't add #include guard (#ifndef ...) there will be multiple definitions of function. But it seems that MATLAB is handling this issue.

I was using this scheme not to call addpath many times:

try
    f(sample args);
catch err
    addpath('lib');
end

But now I think it's not necessary.

Upvotes: 4

Views: 1738

Answers (2)

Pursuit
Pursuit

Reputation: 12345

Multiple calls to addpath do not create multiple functions, so from a correctness point of view there is no problem with using addpath multiple times.

However, addpath is a relatively slow operation. You shouldn't call it within a function that may be called many times during normal operation.


Edit:

Also, rather than relying on try/catch to check the current state of your path, you can check the path directly. See examples here: https://stackoverflow.com/a/8238096/931379.

Upvotes: 3

Jacob
Jacob

Reputation: 34621

#include adds a specific header file. addpath merely adds a folder to the search path and does not add any code to your program. Think of it as adding directories to search for header files in C++ (e.g. in Visual Studio, it's "Additional Include Directories" and g++, it's implemented with -I).

Also, I think addpath checks if the folder has already been added, so you're really not doing anything with the repeated calls to addpath('lib').

Upvotes: 5

Related Questions