Search code examples
matlabcell-array

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


I want to check if directories exist but work them in a cell-array. Matlab where the data is in the cell array in fullDirectories

home='/home/masi/';
directories={ 'Images/Raw/'; 'Images/Data/'; 'Images/Series/' };
fullDirectories = strcat(home, directories);

I can check one directory by exist('/home/masi/', 'dir');. Pseudocode

existCellArray(fullDirectories, 'dir-cell'); 

Matlab: 2016a
OS: Debian 8.5


Solution

  • Here's one approach.

    %%% 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
    

    Note that one shouldn't automatically have a dislike for loops; I feel that in this case it is preferable:

    • it is efficient
    • it is clear, readable, debuggable code (whereas the output from cellfun is cryptic and hard to put to further use)
    • it allows for custom handling
    • a good for loop can actually be faster:

      >> 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.