Questions about using genpath()
15 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(3 个)
matt dash
2014-12-29
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 个评论
matt dash
2014-12-29
Yes, and that folder must be on your path already in order for your code to work.
per isakson
2014-12-29
编辑:per isakson
2014-12-29
" trying to add the search path for the functions to the path"   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
0 个评论
Image Analyst
2014-12-29
编辑:Image Analyst
2014-12-29
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Search Path 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!