← Back to homepage

Devlog — Transpose a Matrix in Clojure Apr 10, 2018

Today I learned a neat trick how to transpose a matrix (vector of vectors) in a very concise manner in Clojure.

Assume that you have a data structure like this:

(def input [[1 2 3]
            [4 5 6]
            [7 8 9]])

And that you need to get a data structure like this:

(def output [[1 4 7]
             [2 5 8]
             [3 6 9]])

By applying (apply mapv vector input) you will get the expected result. I discovered the solution on Stack Overflow.

Here’s an explanation, in my own words: