Combine and average several *.mat files
4 views (last 30 days)
Show older comments
Michael Henry
on 26 Feb 2021
Commented: Michael Henry
on 26 Feb 2021
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
0 Comments
Accepted Answer
Walter Roberson
on 26 Feb 2021
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.
3 Comments
Walter Roberson
on 26 Feb 2021
save(outfile, '-struct', 'outdata');
The line
outdata.(varname) = meandata;
is building a struct (structure) with one field for each variable name. The save() with the magic -struct option tells MATLAB to save each field of the struct as a separate variable.
More Answers (0)
See Also
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!