How to find all specified files in a specified path in Matlab?matlab 如何查找指定路径下的所有指定文件

9 visualizaciones (últimos 30 días)
Matlab 如何遍历所有文件下以及子文件中的模型文件(.mdl ,.slx)
How Matlab Traverses Model Files in All Files and Subfiles

Respuesta aceptada

Xiaoning.Wang
Xiaoning.Wang el 13 de Dic. de 2024
可以查看两个help 文件
listing = dir('*.txt'); % 列出当前文件夹中所有的txt文件
listing = dir('*.txt'); % 返回当前文件夹下所有.txt文件的信息
listing = dir('**/*.txt'); % 返回当前文件夹及子文件夹中所有.txt文件的信息
映射出
listing1 = dir('Z:/model/**/*.slx');
listing2 = dir('Z:\model\**\*.slx');
如果你想查询两个不同格式文件的模型
listing = [dir('**\*.slx');dir('**\*.mdl')]

Más respuestas (2)

xingxingcui
xingxingcui el 13 de Dic. de 2024
你可以使用 dir 函数结合递归来遍历文件夹及其子文件夹中的所有 .mdl.slx 文件。以下是一个示例代码:
function files = findModels(directory)
% Initialize an empty cell array to store model file paths
files = {};
% Get a list of all files and folders in the specified directory
fileList = dir(directory);
% Loop through the files/folders
for i = 1:length(fileList)
% Skip the '.' and '..' entries
if strcmp(fileList(i).name, '.') || strcmp(fileList(i).name, '..')
continue;
end
% Get the full path of the current file/folder
fullPath = fullfile(directory, fileList(i).name);
% If it's a folder, recurse into it
if fileList(i).isdir
files = [files, findModels(fullPath)]; % Recursion
else
% If it's a model file, add it to the list
if endsWith(fileList(i).name, {'.mdl', '.slx'})
files = [files, fullPath];
end
end
end
end
调用 findModels 函数并传入目录路径,函数将返回该目录及所有子目录中 .mdl.slx 文件的路径。
  1 comentario
Lei
Lei el 31 de Mzo. de 2025
挺好的,如果这个function这么写,就具有很好的普适性了,很多类型的文件都能用了。
function files = findModels(directory,FileType)
% Initialize an empty cell array to store model file paths
files = {};
% Get a list of all files and folders in the specified directory
fileList = dir(directory);
% Loop through the files/folders
for i = 1:length(fileList)
% Skip the '.' and '..' entries
if strcmp(fileList(i).name, '.') || strcmp(fileList(i).name, '..')
continue;
end
% Get the full path of the current file/folder
fullPath = fullfile(directory, fileList(i).name);
% If it's a folder, recurse into it
if fileList(i).isdir
files = [files, findModels(fullPath,FileType)]; % Recursion
else
% If it's a model file, add it to the list
if endsWith(fileList(i).name, FileType)
files = [files, fullPath];
end
end
end
end

Iniciar sesión para comentar.


埃博拉酱
埃博拉酱 el 13 de Dic. de 2024
如果你只需要文件名,可以用ls
ls *.mdl
ls *.slx

Categorías

Más información sobre Simulink Environment Customization en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by