我想检查目录是否存在但是在单元数组中工作。
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
操作系统:Debian 8.5
答案 0 :(得分:3)
您可以使用cellfun
:
我从这里做了例子:How to apply cellfun (or arrayfun or structfun) with constant extra input arguments?
该示例使用匿名函数:
cellfun(@(x)exist(x, 'dir'), fullDirectories)
答案 1 :(得分:3)
这是一种方法。
%%% 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
请注意,不应该自动不喜欢循环;我觉得在这种情况下,首选:
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.