我在外置硬盘上有一个文件夹,有50个以上的文件夹,每个文件夹有2000多个文件。 50个文件夹中的每个文件夹都没有子文件夹。我想在MATLAB搜索路径中添加所有文件,因此
我执行了addpath(genpath(...))
。大约需要5分钟。如果文件夹在搜索路径上,我不想再次重复操作。我如何确定?
我知道我可以使用which
测试文件是否在搜索路径上,但我想看看主文件夹(有50个子文件夹)和子文件夹是否在搜索路径上。我该怎么做?
我甚至尝试过使用exist
命令,但即使文件夹不在搜索路径上,它也会给我非零值。
答案 0 :(得分:3)
单个目录搜索案例
%%// path_to_be_searched is the folder or directory to be detected
%%// to be in path or not
%%// colon is the separator used for paths under Linux.
%%// For Windows and others, it needs to be investigated.
path_list_cell = regexp(path,pathsep,'Split')
if any(ismember(path_to_be_searched,path_list_cell))
disp('Yes, this directory is in MATLAB path');
else
disp('No, this directory is not in MATLAB path');
end
主目录以及带有添加选项的子目录搜索案例
对于与子目录搜索一起的基本路径,以下代码将尝试查找每个子目录以及基本路径的匹配,并添加缺少的路径。因此,即使您有选择地从路径中删除了任何子目录甚至基本路径,此代码也会负责添加路径中缺少的所有内容。
%%// basepath1 is the path to the main directory with sub-directories that
%%// are to detected for presence
basepath_to_be_searched = genpath(basepath1)
basepath_list_cell = regexp(basepath_to_be_searched,pathsep,'Split')
%%// Remove empty cells
basepath_list_cell = basepath_list_cell(~cellfun(@isempty,basepath_list_cell))
path_list_cell = regexp(path,pathsep,'Split');
ind1 = ismember(basepath_list_cell,path_list_cell)
%%// Add the missing paths
addpath(strjoin(strcat(basepath_list_cell(~ind1),pathsep),''))
%%// strjoin is a recent MATLAB addition and is also available on file-exchange -
%%// http://www.mathworks.in/matlabcentral/fileexchange/31862-strjoin
答案 1 :(得分:0)
旧问题,但这是通过拆分path()
字符串使用单元格数组的另一种方法。不知道对于大量文件夹,它是否比regexp
方法更慢/更快,但是我发现它在概念上更简单。
首先,创建一个用于检查单个路径的函数。该函数使用p_array=strsplit(path(),pathsep);
创建单元格数组,然后使用any(strcmp(p_array,folder_to_search_for))
检查要查找的文件夹是否在单元格数组中。它只会匹配完整的字符串。
function folder_in_path=checkPath(folder_to_search_for)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% folder_in_path=checkPath(folder_to_search_for)
%
% Input:
% folder_to_search_for string, the folder to check
%
% Output:
% folder_in_path 1 if in path, 0 if not in path
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create a cell array with each folder as a cell
p_array=strsplit(path(),pathsep);
% search the cell array for your folder_to_search_for
if any(strcmp(p_array,folder_to_search_for))
folder_in_path=1;
else
folder_in_path=0;
end
end
因此,要检查存储在top_level_dir
中的顶级目录的所有子目录并添加缺少的子目录:
% generate cell array of all the subdirs in top_level_dir:
allthesubdirs=strsplit(genpath(top_level_dir),pathsep);
% check each one and add to path if not there
for i_fo=1:numel(allthesubdirs)
if ~checkPath(allthesubdirs{i_fo})
disp(['adding ',allthesubdirs{i_fo},' to the path'])
addpath(allthesubdirs{i_fo})
else
disp([allthesubdirs{i_fo},' is already in the path'])
end
end