8
$\begingroup$

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}};

enter image description here

I want to take the average of each cell [i,j] over time by considering the number of non-zero elements only as follows:

Blockquote

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.

$\endgroup$
9
$\begingroup$
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

$\endgroup$
  • $\begingroup$ Your answers are perfect, just the type of answers I was thinking of. The first answer looks more elegant, though. $\endgroup$ – Tugrul Temel Oct 25 '18 at 19:28
  • $\begingroup$ Thank you @TugrulTemel for the accept and kind words. $\endgroup$ – kglr Oct 25 '18 at 19:30
  • 2
    $\begingroup$ First solution gives a warning on M11.3 Power::infy: Infinite expression 1/0 encountered. $\endgroup$ – OkkesDulgerci Oct 25 '18 at 19:34
  • $\begingroup$ Thank you @OkkesDulgerci. Forgot to Quiet. $\endgroup$ – kglr Oct 25 '18 at 19:39
  • 1
    $\begingroup$ @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. $\endgroup$ – Tugrul Temel Oct 25 '18 at 19:41
6
$\begingroup$
Total[{t1, t2, t3}]/Clip[Total[Unitize@{t1, t2, t3}], {1, Infinity}]
$\endgroup$
5
$\begingroup$

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.