Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

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).

local a = {}

for x = 1, n do
  local t = {}
  for y = 1, m do
    t[y] = {x, y}
  end
  a[x] = t
end
  
local b = {}

for y = 1, m do
  local t = {}
  for x = 1, n do
    t[x] = a[x][y]
  end
  b[y] = t
end
(def a [[1 2 3] [4 5 6] [7 8 9]])
(def b (apply (partial mapv vector) a))

New implementation...
< >
tkoenig