Combine and average several *.mat files
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2021년 2월 26일
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
Walter Roberson
2021년 2월 26일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!