How to find all specified files in a specified path in Matlab?matlab 如何查找指定路径下的所有指定文件
Mostrar comentarios más antiguos
Matlab 如何遍历所有文件下以及子文件中的模型文件(.mdl ,.slx)
How Matlab Traverses Model Files in All Files and Subfiles
Respuesta aceptada
Más respuestas (2)
xingxingcui
el 13 de Dic. de 2024
Hi, @Xiaoning.Wang
你可以使用 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
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
埃博拉酱
el 13 de Dic. de 2024
如果你只需要文件名,可以用ls
ls *.mdl
ls *.slx
Categorías
Más información sobre Model, Block, and Port Callbacks en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!