5

将具有相同扩展名的文件夹中的所有文件加载到 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;
4

2 回答 2

7

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

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

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

于 2013-04-04T12:54:26.783 回答
0

如果要从目录中导入所有函数,可以使用 addpath :

在 matlab 中,您位于 c:\matlab\work 目录中,然后点击:

addpath directory_where_all_my_functions_are

导入所有功能c:\matlab\work\directory_where_all_my_function_are

help addpath在 matlab 中获取更多信息

于 2016-10-18T12:53:26.880 回答