#MATL, 20 bytes
XJZyXyi:"!J21ドル!*s1$e
###Explanation
This avoids the matrix multiplication doing it manually, by means of element-wise multiplication with broadcast. Specifically, to multiply matrices A and B, both of size s×ばつs:
- Transpose
A. - Permute the dimensions of
Bsuch thatBis "turned" with a rotation axis along the first dimension, giving an s×ばつs 3D array, sayC. - Multiply each element of
Atransposed times each element ofC, with implicit broadcast. This means thatAis automatically replicated s times along the third dimension, andCis replicated s times along the second, to make them both s×ばつs×ばつs before the actual element-wise multiplication - Sum along the first dimension to yield a ×ばつs×ばつs array.
- Squeeze the leading singleton dimension out, to produce an s×ばつs result.
Commented code:
XJ % take matrix A. Copy to clipboard J
ZyXy % generate identity matrix of the same size
i: % take exponent n. Generate range [1 2 ... n] (possibly empty)
" % for each element in that range
! % transpose original A, or matrix with accumulated product
J % paste A
21ドル! % permute dimensions: rotation along first dimension axis
* % element-wise multiplication with broadcast
s1$e % squeeze out singleton dimension
% end for. Display
Luis Mendo
- 106.7k
- 10
- 139
- 382