MATLAB: Load several .mat files with n x n matrices and compute average

matmatrixn x nnxn

Hi there,
I'm new to working with matlab. I have experience with bash shell scripts. I have a bunch of .mat files that contain n x n matrices like this toy example:
>> load('matrix1.mat')
>> load('matrix2.mat')
>> m1
m1 =
1 2 3
2 1 5
3 6 1
>> m2
m2 =
1 3 5
2 1 5
4 9 1
I have two questions:
1. How can I automatically loop through -say- 100 of these to load them into matlab?
2. If they are loaded (in some way), how can I perform calculations on the cells in the matrices such as computing the average across them? In the example below I'm looking for
mAVG =
1 2.5 4
2 1 5
3.5 7.5 1
Thanks so much!

Best Answer

If the variables are all the same 2D size, then the most efficient thing to do is load them one at a time and store the value into a slice of an array. Then once you have all of the data loaded, you can mean() across the third dimension.
dinfo = dir('matrix*.mat');
nfile = length(dinfo);
if nfile == 0
avg = [];
warning('There were no input files');
else
filestruct = load(dinfo(1).name);
fn = fieldnames(filestruct);
thisvar = filestruct.(fn{1});
orig_size = size(thisvar);
input_data = [thisvar(:), zeros(numel(thisvar), nfile-1, class(thisvar))];
for K = 2 : nfile
filestruct = load(dinfo(K).name);
fn = fieldnames(filestruct);
thisvar = filestruct.(fn{1});
if ~isequal(size(thisvar), orig_size)
error('file "%s" has a different size of matrix than the first file "%s"', dinfo(K).name, dinfo(1).name);
end
input_data(:,K) = thisvar(:);
end
input_data = reshape(input_data, [orig_size, nfile]);
avg = mean(input_data, ndim(input_data));
end
(with data of an unknown number of dimensions, it turned out to be easiest to store the data as columns and reshape afterwards.)