【问题标题】:MATLAB: Load files from folder by extensionMATLAB:按扩展名从文件夹加载文件
【发布时间】:2019-04-11 23:57:07
【问题描述】:

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

【问题讨论】:

    标签: matlab filesystems


    【解决方案1】:

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

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

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

    【讨论】:

    • 当你在它的时候,如果你从'c:\myfolder'以外的文件夹调用这个函数并且'c:\myfolder'不在你的路径中,你将不得不使用load( fullfile( 'c:\myfolder', files(k).name ), '-ascii' );
    • @Shai 再次,你是对的。但是,我给出这个示例只是为了配合我使用dir 命令的建议,而不是关于在 MATLAB 中处理文件的完整教程。
    【解决方案2】:

    如果你想从一个目录中导入所有函数,你可以使用 addpath :

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

    addpath directory_where_all_my_functions_are
    

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

    help addpath 在 matlab 中获取更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多