gpt4 book ai didi

MATLAB:按扩展名从文件夹加载文件

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:03 24 4
gpt4 key购买 nike

将具有相同扩展名的文件夹中的所有文件加载到 MATLAB 中的最简单方法是什么?

我以前的解决方案:

%%% Will load a file if its filename is provided
%%% USAGE: (Best save data to a variable to work with it.)
%%% >> x = loadwrapper('<file_name>')
%%% ... and then use 'x' all the way you want.
%%% <file_name> works with absolute and relative paths, too.

function [ loaded_data ] = loadwrapper( file_name )

files = dir(file_name);
loaded_data = load(files.name);

end

%%% put this in a new script, in a function it WILL NOT WORK!
%%% and fix your paths, ofc. i left mine in here on purpose.


%%% SETTINGS
folderName='/home/user/folder/';
extension='*.dat';


%%% CODE
concattedString=strcat(folderName, extension);
fileSet=dir(concattedString);

% loop from 1 through to the amount of rows
for i = 1:length(fileSet)

% load file with absolute path,
% the fileSet provides just the single filename
load (strcat(folderName, fileSet(i).name));

end


%%% TIDY UP
%%% only imported files shall stay in workspace area
clear folderName;
clear extension;
clear concattedString;
clear fileSet;
clear i;

最佳答案

您可以使用dir 来获取所有需要的文件。然后您可以使用 for 循环遍历它们并为每个调用 load。例如,以下内容:

files = dir('C:\myfolder\*.txt');
for k = 1:length(files)
load(files(k).name, '-ascii')
end

加载“C:\myfolder”中扩展名为“txt”的所有文件。

关于MATLAB:按扩展名从文件夹加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com