如何将元胞数组应用于带有目录的 Matlab exist()?

How to Apply Cell-array to Matlab's exist() with directories?

我想检查目录是否存在,但要在元胞数组中处理它们。 Matlab,其中数据在 fullDirectories

中的元胞数组中
home='/home/masi/';
directories={ 'Images/Raw/'; 'Images/Data/'; 'Images/Series/' };
fullDirectories = strcat(home, directories);

我可以通过exist('/home/masi/', 'dir');查看一个目录。 伪代码

existCellArray(fullDirectories, 'dir-cell'); 

Matlab: 2016a
OS:Debian 8.5

您可以使用 cellfun

我从这里举了个例子:How to apply cellfun (or arrayfun or structfun) with constant extra input arguments?

示例使用匿名函数:

cellfun(@(x)exist(x, 'dir'), fullDirectories)

这是一种方法。

%%% in file existCellArray.m
function Out = existCellArray (FullDirs)
% EXISTCELLARRAY - takes a cell array of *full* directory strings and tests if
%   they exist.

  MissingDirs = {};
  for i = 1 : length(FullDirs)
    if exist(FullDirs{i}, 'dir') 
      continue
    else 
      MissingDirs{end+1} = FullDirs{i}; 
    end
  end

  if isempty(MissingDirs); % Success
    Out = true; 
    return; 
  else % Failure: Missing folders detected. Print diagnostic message
    fprintf('Folder %s is missing\n', MissingDirs{:})
    Out = false;
  end
end

%%% in your console session:
Home = '/home/tasos/Desktop';
Dirs = {'dir1/subdir1', 'dir2/subdir2', 'dir3/subdir3'};
FullDirs = fullfile(Home, Dirs); % this becomes a cell array!
existCellArray (FullDirs)

%%% console output:
Folder /home/tasos/Desktop/dir2/subdir2 is missing
Folder /home/tasos/Desktop/dir3/subdir3 is missing
ans = 0

请注意,人们不应该自动厌恶循环;我觉得在这种情况下 preferable:

  • 效率高
  • 它是清晰、可读、可调试的代码(而 cellfun 的输出是神秘的,难以进一步使用)
  • 它允许自定义处理
  • 一个好的for循环实际上可以更快:

    >> tic; for i = 1 : 1000; cellfun(@(x)exist(x, 'dir'), FullDirs); end; toc
    Elapsed time is 3.66625 seconds.
    >> tic; for i = 1 : 1000; existCellArray(FullDirs); end; toc;
    Elapsed time is 0.405849 seconds.