Averaging multiple 2D data sets

I have multiple data sets, each of which is a 2D matrix. I want to construct a new 2D Matrix in which each element is the average of that element for all the original data sets. i.e

NewMatrix[i][j] =1/N *(Matrix1[i][j] + Matrix2[i][j] + … + MatrixN[i][j])

I can’t quite figure out how to do it in Mathematica.





You might find some of the tutorials (espcially those on linear algebra) useful: reference.wolfram.com/mathematica/guide/…
– bill s
Jul 22 ’13 at 14:04


1 Answer


This is a pretty basic question but since you’re new here let me get you started. Many functions in Mathematica are natively designed to work on vectors, arrays, and tensors. That means that such an operation is or at least may be directly analogous to the non-array form. Suppose you have:

a1 = RandomInteger[9, {5, 5}];
a2 = RandomInteger[9, {5, 5}];
a3 = RandomInteger[9, {5, 5}];

You then need merely:

(a1 + a2 + a3) / 3


Mean[{a1, a2, a3}]

Just as you would if a1, a2 and a3 were individual numbers. This will be much faster than a manual procedural operation, unless you are going to compile that procedural code.

A sidebar

You could define all three arrays at once using:

{a1, a2, a3} = RandomInteger[9, {3, 5, 5}];

There is a subtle yet important difference however. This more concise form will unpack the packed integer array that is produced by RandomInteger, resulting in slower numeric operations on those expressions.



Subtle indeed!. You’ve already told us that arrays are not packed automatically and I’ve since learned that On[“Packing”] tells us when a command is unpacking an array, but is there any resource that should clue us in that RandomInteger (or any other function) will be returning a packed array?
– bobthechemist
Jul 22 ’13 at 12:50



@bobthechemist — I know he has the name “Mr.Wizard”, but how does he know that stuff?
– Jagra
Jul 22 ’13 at 13:15



Ah, thanks very much. I’m more accustomed to coding environments like java where you have to deal with each element individually, I didn’t realise Mathematica dealt with matrices in such an elegant way.
– user1369909
Jul 22 ’13 at 13:17



@bob You can check if an array is packed with Developer`PackedArrayQ. I’m not sure if it is expressly stated that RandomInteger, Range, etc. return packed arrays, but it would be disappointing if they did not. Be aware that unpacked arrays may be automatically packed on-the-fly by functions which auto-compile (at some threshold) such as Map and Fold, e.g. Map[N, list] on a list of more than 100 unpacked integers will return a packed list of reals. Also see this question for avoiding or understanding unpacking.
– Mr.Wizard♦
Jul 22 ’13 at 13:59



@Jagra Thanks for making me smile. :^) What I know has been learned from roughly equal parts of experimentation, reading MathGroup and other resources at library.wolfram.com, and participation on this site (and StackOverflow before it).
– Mr.Wizard♦
Jul 22 ’13 at 14:01