3

やりたいことは2つあります。

  1. ディレクトリ内のすべてのディレクトリ名のリストを取得し、
  2. ディレクトリ内のすべてのファイル名のリストを取得する

MATLAB でこれを行うにはどうすればよいですか?

今、私はしようとしています:

dirnames = dir(image_dir);

しかし、それはオブジェクトのリストを返すと思います。size(dirnames)属性の数をdirnames.name返し、最初のディレクトリの名前のみを返します。

4

3 に答える 3

5

関数DIRは、実際には、指定されたディレクトリ内のファイルまたはサブディレクトリごとに 1 つの構造要素を持つ構造配列を返します。構造体配列からデータを取得する場合、ドット表記でフィールドにアクセスすると、構造体要素ごとに 1 つの値を持つフィールド値のコンマ区切りリストが返されます。このコンマ区切りのリストは、角括弧内に配置することでベクトルに収集でき、中括弧内に配置することでセル配列に収集できます。[]{}

私は通常、次のように論理インデックスを使用して、ディレクトリ内のファイルまたはサブディレクトリ名のリストを取得したいと考えています。

dirInfo = dir(image_dir);            %# Get structure of directory information
isDir = [dirInfo.isdir];             %# A logical index the length of the 
                                     %#   structure array that is true for
                                     %#   structure elements that are
                                     %#   directories and false otherwise
dirNames = {dirInfo(isDir).name};    %# A cell array of directory names
fileNames = {dirInfo(~isDir).name};  %# A cell array of file names
于 2011-02-02T04:20:00.467 に答える
2

いいえ、あなたは dirnames.name が返すものについて間違っています。

D = dir;

これは構造体配列です。ディレクトリのリストが必要な場合は、これを行います

isdirlist = find(vertcat(D.isdir));

または、ここで cell2mat を使用することもできました。D.name だけを試すと、カンマ区切りのリストが返されることに注意してください。ただし、すべての名前をセル配列として簡単に取得できます。

nameslist = {D.name};
于 2011-02-01T23:45:02.363 に答える
0

「image_dir」がディレクトリの名前であると仮定すると、次のコードは、どの項目がディレクトリで、どの項目がファイルであるかを判別する方法と、それらの名前を取得する方法を示しています。ここまで来たら、ディレクトリのみまたはファイルのみのリストを作成するのは簡単です。

dirnames = dir(image_dir);
for(i = 1:length(dirnames))
   if(dirnames(i).isdir == true)
      % It's a subdirectory
      % The name of the subdirectory can be accessed as dirnames(i).name
      % Note that both '.' and '..' are subdirectories of any directory and
      % should be ignored
   else
      % It's a filename
      % The filename is dirnames(i).name
   end
end
于 2011-02-01T23:54:01.300 に答える