Combine and average several *.mat files

5 vues (au cours des 30 derniers jours)
Michael Henry
Michael Henry le 26 Fév 2021
Commenté : Michael Henry le 26 Fév 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

Réponse acceptée

Walter Roberson
Walter Roberson le 26 Fév 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 commentaires
Walter Roberson
Walter Roberson le 26 Fév 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.
Michael Henry
Michael Henry le 26 Fév 2021
Thank you so much. It works perfectly.. :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by