Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

include

matlab

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.

like image 748
Mohammad Moghimi Avatar asked Feb 21 '23 12:02

Mohammad Moghimi


2 Answers

#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').

like image 61
Jacob Avatar answered Feb 24 '23 02:02

Jacob


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.

like image 31
Pursuit Avatar answered Feb 24 '23 02:02

Pursuit