MATLAB: Combine and average several *.mat files

combinemat files

Hello
I have a problem and I need your help, please.
I have several *.mat files and each file has the same variables but with different values. I would like to find the average value of each variable (which is basically a row of numbers) and then create a new mat file to plot the averaged results.
I have been looking over the internet but I didn't find the correct way to do it.
Thank you for your help!
M.H

Best Answer

matdir = 'name_of_directory'; %could be '.'
outfile = 'path/to/output.mat';
dinfo = dir(fullfile(matdir, '*.mat'));
filenames = fullfile({dinfo.folder}, {dinfo.name});
numfiles = length(filenames);
alldata = cell(numfiles, 1);
for K = 1 : numfiles
thisfile = filenames{K};
alldata{K} = load(thisfile);
end
%we take on trust that "each file has the same variables"
varnames = fieldnames(alldata{1});
outdata = struct();
for varidx = 1:length(varnames)
varname = varnames{varidx};
extracted_data = cellfun(@(C) C.(varname), alldata, 'uniform', 0);
dim = ndims(extracted_data{1});
meandata = mean(cat(dim+1, extracted_data{:}),dim+1);
outdata.(varname) = meandata;
end
save(outfile, '-struct', outdata);
This code does not assume anything about the shape of the data -- does not assume it is vector or 2d or whatever. It does, however, assume that for any one variable it is the same shape in all files, and that the data is numeric, and that what you want is the mean between files. It also assumes that the exact same variable names are in every file (but not necessarily in the same order in each file.)
This is not the only possible implementation for taking the mean, but it has the advantage of being simple and easy to understand, and in not relying on order of variables in the files.