Questions about using genpath()

조회 수: 12 (최근 30일)
Sam
Sam 2014년 12월 29일
댓글: matt dash 2014년 12월 29일
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?

답변 (3개)

matt dash
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
Sam
Sam 2014년 12월 29일
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 2014년 12월 29일
Yes, and that folder must be on your path already in order for your code to work.

댓글을 달려면 로그인하십시오.


per isakson
per isakson 2014년 12월 29일
편집: per isakson 2014년 12월 29일
" 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 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.

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by