# Averaging elements of a list of matrices over time

Suppose that I have a time series of a matrix, say, for 3 periods.

t1={{0,3,0},{6,0,0},{3,6,0}};
t2={{0,6,0},{3,0,3},{0,6,0}};
t3={{0,3,6},{3,0,6},{3,3,0}}; I want to take the average of each cell [i,j] over time by considering the number of non-zero elements only as follows: I went through the documentation of Matrix Operations but I could not find any thing close to what I describe above. Of course, one can use Flatten, Sum and Partition to accomplish what I want. However, I like to have a more elegant way to do the job using matrix structure.

Quiet @ Block[{Indeterminate = 0}, Total[#] / Total[Unitize @ #]] & @ {t1, t2, t3}

% // MatrixForm // TeXForm


$$\left( \begin{array}{ccc} 0 & 4 & 6 \\ 4 & 0 & \frac{9}{2} \\ 3 & 5 & 0 \\ \end{array} \right)$$

Also

Total[{t1, t2, t3}] / (Total[Unitize @ {t1, t2, t3}] /. 0 -> 1)


same result

• Your answers are perfect, just the type of answers I was thinking of. The first answer looks more elegant, though. – Tugrul Temel Oct 25 '18 at 19:28
• Thank you @TugrulTemel for the accept and kind words. – kglr Oct 25 '18 at 19:30
• First solution gives a warning on M11.3 Power::infy: Infinite expression 1/0 encountered. – OkkesDulgerci Oct 25 '18 at 19:34
• Thank you @OkkesDulgerci. Forgot to Quiet. – kglr Oct 25 '18 at 19:39
• @kglr: Yes, I was going to ask why we receive warnings from the first method. There is no room for warning because if all elements are zero, then the average is zero. – Tugrul Temel Oct 25 '18 at 19:41
Total[{t1, t2, t3}]/Clip[Total[Unitize@{t1, t2, t3}], {1, Infinity}]


You can do it as a pipeline of functions, using MapThread; a properly placed Replace gets rid of the warnings:

MapThread[
List /* DeleteCases /* Replace[{} -> {0}] /* Mean,
{t1, t2, t3}, 2]

(* {{0, 4, 6}, {4, 0, 9/2}, {3, 5, 0}} *)