将具有相同扩展名的文件夹中的所有文件加载到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;
答案 0 :(得分:7)
您可以使用dir
获取所有需要的文件。然后你可以用for循环遍历它们并为每个循环调用load
。例如,以下内容:
files = dir('C:\myfolder\*.txt');
for k = 1:length(files)
load(files(k).name, '-ascii')
end
加载&#34; C:\ myfolder&#34;中的所有文件使用扩展名&#34; txt&#34;。
答案 1 :(得分:0)
如果要从目录导入所有函数,可以使用addpath:
在matlab中,您位于c:\ matlab \ work目录中,然后点击:
addpath directory_where_all_my_functions_are
导入c:\matlab\work\directory_where_all_my_function_are
help addpath
了解更多信息