Load Multiple .mat Files to Matlab workspace

前端 未结 3 541
抹茶落季
抹茶落季 2020-12-20 02:52

I\'m trying to load several .mat files to the workspace. However, they seem to overwrite each other. Instead, I want them to append. I am aware that I can do something li

相关标签:
3条回答
  • 2020-12-20 03:20

    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

    0 讨论(0)
  • 2020-12-20 03:21

    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.

    0 讨论(0)
  • 2020-12-20 03:34

    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
    
    0 讨论(0)
提交回复
热议问题