在matlab路径中查找重复项

时间:2014-02-21 09:50:44

标签: matlab path

matlab路径中的重复是一件麻烦事,因为你无法控制哪一个被执行。处理重复的第一步是找到它们。如何在matlab路径中找到重复的.m文件?

2 个答案:

答案 0 :(得分:4)

嗯,这本身并不是一项艰巨的任务。我们必须列出路径中的所有.m文件,并找到同一文件的多次出现。我们可以混合使用pathwhatunique函数。

function find_duplicate()

P=path;
P=strsplit(P, pathsep());
% mydir='/home/myusername/matlabdir';
% P=P(strncmpi(mydir,P,length(mydir)));
P=cellfun(@(x) what(x),P,'UniformOutput',false);
P=vertcat(P{:});
Q=arrayfun(@(x) x.m,P,'UniformOutput',false); % Q is a cell of cells of strings
Q=vertcat(Q{:});
R=arrayfun(@(x) repmat({x.path},size(x.m)),P,'UniformOutput',false); % R is a cell of cell of strings
R=vertcat(R{:});
[C,ia,ic]=unique(Q);
for c=1:numel(C)
    ind=strcmpi(C{c},Q);
   if sum(ind)>1
       fprintf('duplicate %s at paths\n\t',C{c});
       fprintf('%s\n\t',R{ind});
       fprintf('\n');
   end
end

end

不是处理完整的Matlab路径,而是可以将搜索重复项限制为自己的文件夹。要做到这一点,只需取消注释第三行并用您选择的目录名替换。

答案 1 :(得分:0)

要分析给定文件夹(递归),您可以按以下步骤操作。

folder = 'C:\Users\Luis\Desktop'; %// folder to be analyzed
[ success files id ] = fileattrib(['.' filesep '*']); %// this is recursive
[fullNames{1:numel(files)}] = deal(files.Name);
isMFile = cellfun(@(s) all(s(end-1:end)=='.m'), fullNames);
fullNames = fullNames(isMFile);  %// keep only m-files
F = numel(fullNames);
start = cellfun(@(s) find(s==filesep,1,'last'), fullNames);
names = arrayfun(@(k) fullNames{k}(start(k)+1:end), 1:F, 'uni', 0); %// file name
[ii jj] = ndgrid(1:F); %// generate all pairs
equal = arrayfun(@(n) strcmp(names{ii(n)},names{jj(n)}), 1:F^2); %// test each
%// pair of files
equal = reshape(equal,F,F) - eye(F); %// equality with oneself doesn't count
isDuplicate = any(equal); %// it is a duplicate if it has some equal file
duplicates = fullNames(isDuplicate); %// cell array with full names of duplicates

要测试整个路径,请在路径中的所有文件夹的循环中使用上面的代码。你可以按照以下几行(我没有测试它,因为我没有strsplit函数):

p = path;
p = strsplit(p,';');
duplicates = {};
for kk = numel(p)
    folder = p{kk};
    [ success files id ] = fileattrib(['.' filesep '*']);
    [fullNames{1:numel(files)}] = deal(files.Name);
    isMFile = cellfun(@(s) all(s(end-1:end)=='.m'), fullNames);
    fullNames = fullNames(isMFile);
    F = numel(fullNames);
    start = cellfun(@(s) find(s==filesep,1,'last'), fullNames);
    names = arrayfun(@(k) fullNames{k}(start(k)+1:end), 1:F, 'uni', 0);
    [ii jj] = ndgrid(1:F);
    equal = arrayfun(@(n) strcmp(names{ii(n)},names{jj(n)}), 1:F^2);
    equal = reshape(equal,F,F) - eye(F);
    isDuplicate = any(equal);
    duplicates = {duplicates, fullNames(isDuplicate)}; %// add previous ones
end