Questions about using genpath()

27 views (last 30 days)
Sam
Sam on 29 Dec 2014
Commented: matt dash on 29 Dec 2014
file_name = 'ExamplesFunctions.m'; %a specific m-file
function_dir = which(file_name); %find the full path of this file
function_dir = function_dir(1:end-length(file_name)); %full path of the file - the file name
addpath(genpath([function_dir, 'Functions'])) %add the path for all functions.
I was trying to add the search path for the functions to the path of the directory (for example if I send my code to a fellow student, so that all functions are automatically found). But when I put a directory 'Functions' (= a directory containing all functions of my program) somewhere else than on the current Matlab directory, Matlab doesn't find this directory 'Functions'.
Maybe I'm wrong with the specific purpose of the command 'genpath'? Help someone?

Answers (3)

matt dash
matt dash on 29 Dec 2014
Genpath makes a list of all subfolders below the specified folder. For what you're doing to work, the highest level folder ("Functions") would already need to be on the search path, and your code would add all it's subdirectorys to the search path.
There is no way to automatically add a folder to the path by using "which" on a file that is in that folder. Although it's a little inconvenient, it prevents some stupid stuff from happening (e.g. how far should matlab look for "ExamplesFunctions.m"... should it search your entire computer looking for it? That would take a long time...)
  2 Comments
Sam
Sam on 29 Dec 2014
So, for a specific m-file, the subfolder 'Functions' should be saved in the same folder where this specific m-file was saved?
matt dash
matt dash on 29 Dec 2014
Yes, and that folder must be on your path already in order for your code to work.

Sign in to comment.


per isakson
per isakson on 29 Dec 2014
Edited: per isakson on 29 Dec 2014
" trying to add the search path for the functions to the path" &nbsp I believe that you are looking for addpath, Add folders to search path
You can create the folder, Functions, anywhere on the disk and add the new folder to Matlabs search path with addpath

Image Analyst
Image Analyst on 29 Dec 2014
Edited: Image Analyst on 29 Dec 2014
If the files are not already on the search path, doing which() like you're doing will not find them. I suggest you edit their startup.m file to have code in it like this:
addpath(genpath('C:/Users/otherUser/Documents/MATLAB/work/Sams Functions'));
fprintf('Saving path...\n');
savepath;
filebrowser;
This will add your folder along with its subfolders to their search path and make sure it's there every time they start MATLAB. You might be able to do it just once because of the savepath command, but it can't hurt to put it into their startup.m file just to make sure.

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!