MATLAB:通过扩展名从文件夹加载文件 [英] MATLAB: Load files from folder by extension
本文介绍了MATLAB:通过扩展名从文件夹加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以前的解决方案由我:
%%%如果提供文件名,将加载文件
%%% USAGE :(最好将数据保存到一个变量中来处理它)
%%%>> x = loadwrapper('< file_name>')
%%% ...然后用你想要的方式使用'x'。
%%%< file_name>也有绝对的和相对的路径。
函数[loaded_data] = loadwrapper(文件名)
files = dir(file_name);
loaded_data = load(files.name);
end
和
%%%把这个放在一个新的脚本中,在一个函数中它不会工作!
%%%并修复你的路径,ofc。我故意把我的故事留在这里。
%%% SETTINGS
folderName ='/ home / user / folder /';
extension ='*。dat';
%%%代码
concattedString = strcat(文件夹名,扩展名);
fileSet = dir(concattedString);
从1循环到行数
对于i = 1:length(fileSet)
使用绝对路径加载文件
%fileSet只提供单个文件名
load(strcat(folderName,fileSet(i).name));
结束
%%% TIDY UP
%%%只有导入的文件应保留在工作区域
清除文件夹名称;
明确的扩展;
清除concattedString;
清除fileSet;
清除我;
解决方案
您可以使用 dir
来获取所有需要的文件。然后你可以用for循环遍历它们,并为它们分别调用 load
。例如,以下内容:
pre code files = dir('C:\ myfolder \ * .txt');
for k = 1:length(files)
load(files(k).name,'-ascii')
end
加载扩展名为txt的C:\myfolder中的所有文件。
What is the easiest way to load all files from a folder with the same extension into MATLAB?
Previous solutions by me:
%%% 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
and
%%% 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;
解决方案
You can use dir
to get all desired files. Then you can iterate over them with a for loop and call load
for each. For example, the following:
files = dir('C:\myfolder\*.txt');
for k = 1:length(files)
load(files(k).name, '-ascii')
end
loads all files in "C:\myfolder" with the extension "txt".
这篇关于MATLAB:通过扩展名从文件夹加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文