Load Multiple .mat Files to Matlab workspace
Solution 1
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.
Solution 2
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
CHP
Updated on June 15, 2022Comments
-
CHP almost 2 years
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 like:
S=load(file1) R=load(file2)
etc.
and then append the variables manually.
But there's a ton of variables, and making an append statement for each one is extremely undesirable (though possible as a last resort). Is there some way for me to load .mat files to the workspace (by using the
load()
command without assignment) and have them append? -
CHP almost 12 yearsThis is not quite the answer I wanted but probably the next best thing, given that what I want can't be done. I'll go ahead and accept it.
-
tmpearce almost 12 yearsOnce everything has been loaded, you can use
fieldnames
to figure out all the different variables you have loaded into the structure. You can theneval
to get them into the workspace (instead of just in the structure), "appending" (however you define it) as needed.