Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

3 of 6
added 624 characters in body
Luis Mendo
  • 106.7k
  • 10
  • 139
  • 382

#MATL, 20 bytes

XJZyXyi:"!J21ドル!*s1$e

Try it online!

###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:

  1. Transpose A.
  2. Permute the dimensions of B such that B is "turned" with a rotation axis along the first dimension, giving an s×ばつs 3D array, say C.
  3. Multiply each element of A transposed times each element of C, with implicit broadcast. This means that A is automatically replicated s times along the third dimension, and C is replicated s times along the second, to make them both s×ばつs×ばつs before the actual element-wise multiplication
  4. Sum along the first dimension to yield a ×ばつs×ばつs array.
  5. 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

AltStyle によって変換されたページ (->オリジナル) /