PDA

查看完整版本 : 如何获取MATLAB中特定目录中所有目录名称和/或所有文件的列表?


poster
2019-12-14, 20:13
我想做两件事:


获取目录中所有目录名称的列表,然后
获取目录中所有文件名的列表
如何在MATLAB中执行此操作?

现在,我正在尝试:

dirnames = dir(image_dir); 但我认为那会返回对象列表。 size(dirnames)返回属性的数量, dirnames.name仅返回第一个目录的名称。



回答:

函数DIR (http://www.mathworks.com/help/techdoc/ref/dir.html)实际上返回一个结构数组 (http://www.mathworks.com/help/techdoc/matlab_prog/br04bw6-38.html) ,其中给定目录中的每个文件或子目录具有一个结构元素。当从结构数组中获取数据时 (http://www.mathworks.com/help/techdoc/matlab_prog/br04bw6-38.html#br1v5pf-1) ,使用点符号访问字段将返回以逗号分隔 (http://www.mathworks.com/help/techdoc/matlab_prog/br2js35-1.html)的字段值列表 (http://www.mathworks.com/help/techdoc/matlab_prog/br2js35-1.html) ,每个结构元素一个值。将该逗号分隔的列表放在方括号[]中,可以将其收集到向量中 (http://www.mathworks.com/help/techdoc/math/f1-84864.html) ;也可以通过将其放在花括号{} ,将其存储在单元格数组 (http://www.mathworks.com/help/techdoc/matlab_prog/br04bw6-98.html)中。

我通常喜欢通过使用逻辑索引 (http://www.mathworks.com/help/techdoc/math/f1-85462.html#bq7egb6-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

更多&回答... (https://stackoverflow.com/questions/4869188)