MATLAB Answers

How can I average multiple matrices by element to create a new matrix of the same size?

309 views (last 30 days)
Patrick
Patrick on 2 Oct 2013
Commented: Image Analyst on 20 Apr 2021
I have 31 matrices, each of size 72x144, and each representing a day of the month of January. I would like to have a 32nd matrix, also of size 72x144, which includes the average value for each element in the original 31 matrices. For example, if I have:
A=[1,2,3|2,3,4|3,4,5] B=[2,3,4|3,4,5|4,5,6] C=[3,4,5|4,5,6|5,6,7]
I want:
D=[2,3,4|3,4,5|4,5,6] (the average by element of the originals)
What is the easiest way for me to do this? I have found a few threads here which have answers I don't really understand, as I am relatively unfamiliar with writing codes, for MATLAB or otherwise. I need something easy to understand.
Thanks, Patrick
  2 Comments
Patrick
Patrick on 2 Oct 2013
Azzi, please see my comment in reply to Image Analyst's answer. I was mistakenly unclear about the file names, and that adds some value to the correct answer, I presume. Thanks for your help!

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 2 Oct 2013
meanMatrix = (matrix1 + matrix2 + matrix3 + .... etc...... + matrix 30 + matrix31)/31;
  2 Comments
Image Analyst
Image Analyst on 2 Oct 2013
If you don't already have them in arrays, then you can use the code in the FAQ to read in the arrays from a bunch of files: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
myFolder = 'C:\Documents and Settings\yourUserName\My Documents\My Data Files';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.txt');
txtFiles = dir(filePattern);
for k = 1:length(txtFiles)
baseFileName = txtFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
thisArray = csvread(fullFileName); % Or however you read them in.
if k == 1
sumArray = thisArray;
else
sumArray = sumArray
end
end
meanArray = sumArray / length(txtFiles);

Sign in to comment.

More Answers (3)



Tope Oyelade
Tope Oyelade on 20 Apr 2021
Edited: Image Analyst on 20 Apr 2021
Just add a dot before the '/' as below and you are good to go!
meanMatrix = (matrix1 + matrix2 + matrix3 + .... etc...... + matrix30 + matrix31)./31
  3 Comments
Image Analyst
Image Analyst on 20 Apr 2021
Of course adding and dividing gives you the average - not sure why you said "but" as if something is different from what I said.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!