MATLAB: Average of multiple matrices to create a new matrix with the same dimension.

averagenew matrix

Hi all!!
I want to take a total of 2416 variables named T (2112×2688), find the average of element by element of all the 2416 variables to create a single matrix with the avarege values.
I tried the following code, and I was able to get a single matrix with values, but those values doesn't correspond to the true averege values (I proved it myself with a test using only 10 T variables).
I attacched 2 example .mat files if anyone want to check out.
Thank's very much for any help!!!
Regards, Paulo Beiral.
diret = '/data/processamento_beiral/2';
cd (diret);
files = './*.mat';
dir (files);
arrumado = dir(files);
all = [1 355];
%% Average
for i = 1:length(arrumado)
if str2double(arrumado(i).name(6:8)) >= all(1) && str2double(arrumado(i).name(6:8)) <= all(2)
turb(i) = load(arrumado(i).name);
x = turb(:).T;
x(isnan(x)) = 0;
meanMatrix = x/2416;
end
end

Best Answer

If I am understanding your question right, you are wanting to find average of each element and ignore the nans?
diret = 'New Folder';
cd (diret);
files = './*.mat';
dir(files);
arrumado = dir(files);
all = [1 355];
%% Average
for i = 1:length(arrumado)
if str2double(arrumado(i).name(6:8)) > all(1) && str2double(arrumado(i).name(6:8)) <= all(2)
turb(i) = load(arrumado(i).name);
end
end
x = {turb.T};
x = cellfun(@(x) shiftdim(x,-1),x,'UniformOutput',false)';
x = cell2mat(x);
meanMatrix = squeeze(mean(x,'omitnan'));