用strcmp搜索matlab搜索路径

时间:2016-12-21 12:11:45

标签: matlab

我写了下面的代码。基本上它是检查某些路径是否已经在matlab搜索路径中。如果未找到,则添加路径。

问题是尽管currPath中实际存在路径,但strcmp始终返回零向量。我实际上从currPath复制了一个路径来检查我是否得到了正确的值。不知道为什么会这样?

% get current path
currPath = strsplit(path, ';')';
currPath = upper(currPath);

% check if required paths exist - if not add them
pathsToCheck = ['C:\SOMEFOLDER\MADEUP'];
pathsToCheck = upper(pathsToCheck);

for n = 1 : length(pathsToCheck(:, 1))       
    index = strcmp(currPath, pathsToCheck(n, 1));    
    if sum(index) > 0    
        addpath(pathsToCheck{t, 1}, '-end');          % add path to the end
    end    
 end

% save changes
savepath;

1 个答案:

答案 0 :(得分:2)

问题是你已经将pathsToCheck定义为一个字符数组而不是一个单元格数组(我认为这就是你想要循环它的方式)。 / p>

您可以使用ismember来检查字符串的单元格数组中哪些成员存在于另一个字符串单元格数组中,而不是使用for循环。

% Note the use of pathsep to make this work across multiple operating systems
currentPath = strsplit(path, pathsep);
pathsToCheck = {'C:\SOMEFOLDER\MADEUP'};

exists = ismember(pathsToCheck, currentPath);
% If you want to ignore case: ismember(upper(pathsToCheck), upper(currentPath))

% Add the ones that didn't exist
addpath(pathsToCheck{~exists}, '-end');