Reputation: 1081
Don't know why this isn't working anymore. Very simple. I have a script with a folder in the same path. The folder contains a series of m files for the script to work.
Originally I simply would use
addpath('.../utilities/);
when the script was first run. but recently I started receiving this error
Warning: Name is nonexistent or not a directory: ...\utilities
In path (line 109)
In addpath (line 88)
In Myrunningcode (line 101)
and I don't know why.
I fixed the problem by running the following code
p = mfilename('fullpath');
[filepath,~,~] = fileparts(p);
addpath([filepath,'/utilities/']);
At least I would like to know why this error occurred.
Here is my directory setup. I use windows 10 and matlab 2016a.
Upvotes: 0
Views: 1392
Reputation: 30047
The issue is likely that your current directory (pwd
) is not the same as the file location. The relative directory isn't relative to the current script, it's relative to pwd
, hence why the mfilename
workaround fixes your issue.
The first solution is your own, but you can do it in one line:
addpath( fullfile( fileparts( mfilename('fullpath') ), 'utilities' ) );
Then the quickest way to check if your files are already on the path is using which
:
% Assuming that myFile.m is within the utilities folder, and not shadowed elsewhere.
% If utilities is on the path, which('myFile') will not be empty.
if isempty( which( 'myFile' ) )
addpath( fullfile( fileparts( mfilename('fullpath') ), 'utilities' ) );
end
Alternatively, you could pair the above check with a persistent
flag variable, so you don't have to repeat the check if you re-enter the function.
Note that addpath
isn't particularly slow, it's genpath
you want to avoid if you were to add a load of subdirectories too.
Aside: It's good to use fullfile
instead of manually concatenating with (OS dependent) file separators. Less room for error (e.g. double slashes) even if you're always using the same OS.
Upvotes: 3
Reputation: 35525
The correct way to include a relative folder is:
addpath('./utilities/');
with a single dot.
This has worked (and works) since the existence of relative folders, AFAIK, so you should be able to use it without fear of deprecation
Upvotes: 2