Logo

Programming-Idioms

  • Dart
  • Python

Idiom #188 Matrix multiplication

Perform matrix multiplication of a real matrix a with nx rows and ny columns, a real matrix b with ny rows and nz columns and assign the value to a real matrix c with nx rows and nz columns.

import numpy as np
c = np.matmul(a, b)

You can also use np.matrix instead of np.array. Be careful when using array, because the * operator performs elementwise multiplication.
import numpy as np
c = a @ b

Python 3.5 (PEP465) introduced the @ operator for matrix multiplication.
(defn t [x] (apply (partial mapv vector) x))
(defn v* [u v] (reduce + (mapv * u v)))
(defn shape [a] (comp (partition-all (count a)) (map vec)))

(defn mm [a b]
    (into [] (shape a)
        (for [line a col (t b)]
            (v* line col))))

(def c (mm a b))

New implementation...