Logo

Programming-Idioms

  • Go
  • Python

Idiom #193 Transpose a two-dimensional matrix

Declare two two-dimensional arrays a and b of dimension n*m and m*n, respectively. Assign to b the transpose of a (i.e. the value with index interchange).

import numpy as np
a = np.array([[1,2], [3,4], [5,6]])
b = a.T
b = [*zip(*a)]

"... Another way to think of zip() is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix."
a = [[1,2], [3,4], [5,6]]
b = list(map(list, zip(*a)))
(def a [[1 2 3] [4 5 6] [7 8 9]])
(def b (apply (partial mapv vector) a))

New implementation...
< >
tkoenig