Efficient and compact code for taking the mean of each diagonal (or anti-diagonal) in a 2D matrix without using a for-loop. Works well for large matrices, and is particularly efficient for tall or wide matrices.
Note that a for-loop implementation with the diag() function might be faster, and have lower memory requirement when applied to close to square matrices (especially if the slow mean() function can be avoided).
However, if the mean across diagonals has to be computed for several matrices of the same size (in a loop), the inlined version of this implementation is typically faster. |