Load Multiple .mat Files to Matlab workspace

前端 未结 3 561
抹茶落季
抹茶落季 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: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
    

提交回复
热议问题