MATLAB Answers

0

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

Asked by Paulo Eduardo Beiral on 9 Oct 2019
Latest activity Commented on by meghannmarie on 10 Oct 2019
Hi all!!
I want to take a total of 2416 variables named T (2112x2688), 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

  0 Comments

Sign in to comment.

1 Answer

Answer by meghannmarie on 9 Oct 2019
 Accepted 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'));

  2 Comments

Thank's very much meghannmarie!!
That's exactly what i needed, but there's still a doubt in my mind about the following line:
x = cellfun(@(x) shiftdim(x,-1),x,'UniformOutput',false)';
I read the matlab help about cellfun and shiftdim, but could you explain why do they have to be used in this case?...and specifically, why the "@" before the "(x)"?
Again, thank you for helping!
So we are shifting the dimension on each matrix so each resulting matrix wil be the size of 1x2112x2688. Now we can turn the cell array into a matrix and the matrixes from cells will be concatonated on that first dimension. This sets us up to get the mean on that dimension.
To apply the shiftdim to all the cells, I use cellfun. Since shiftdim requires 2 inputs (the matrix and -1), I use and anonymous function @(x) shiftdim(x,-1) - (you can look anonymous function up in the help). The anonymous function is applying shiftdim(x,-1) to each cell. If I used @shiftdim, I wouldnt be feeding the second input to the function.

Sign in to comment.