Load Multiple .mat Files to Matlab workspace

狂风中的少年 提交于 2019-11-29 12:05:44

Its not entirely clear what you mean by "append" but here's a way to get the data loaded into a format that should be easy to deal with:

file_list = {'file1';'file2';...};
for file = file_list'
    loaded.(char(file)) = load(file);
end

This makes use of dynamic field references to load the contents of each file in the list into its own field of the loaded structure. You can iterate over the fields and manipulate the data however you'd like from here.

It sounds like you have a situation in which each file contains a matrix variable A and you want to load into memory the concatenation of all these matrices along some dimension. I had a similar need, and wrote the following function to handle it.

function var = loadCat( dim, files, varname )
%LOADCAT Concatenate variables of same name appearing in multiple MAT files
%  
%   where dim is dimension to concatenate along,
%         files is a cell array of file names, and
%         varname is a string containing the name of the desired variable

    if( isempty( files ) )
        var = [];
        return;
    end
    var = load( files{1}, varname );
    var = var.(varname);

    for f = 2:numel(files),

        newvar = load( files{f}, varname );
            if( isfield( newvar, varname ) )
                var = cat( dim, var, newvar.(varname) );
            else
                warning( 'loadCat:missingvar', [ 'File ' files{f} ' does not contain variable ' varname ] );
            end
        end 

    end
jason

Clark's answer and function actually solved my situation perfectly... I just added the following bit of code to make it a little less tedious. Just add this to the beginning and get rid of the "files" argument:

[files,pathname] = uigetfile('*.mat', 'Select MAT files (use CTRL/COMM or SHIFT)', ...
   'MultiSelect', 'on'); 

Alternatively, it could be even more efficient to just start with this bit:

[pathname] = uigetdir('C:\');
files = dir( fullfile(pathname,'*.mat') );   %# list all *.mat files
files = {files.name}';                       %# file names

data = cell(numel(files),1);                 %# store file contents
for i=1:numel(files)
    fname = fullfile(pathname,files{i});     %# full path to file
    data{i} = load(fname);                   %# load file
end

(modified from process a list of files with a specific extension name in matlab).

Thanks, Jason

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!