Skip to main content

Command Palette

Search for a command to run...

Transpose a Matrix in Clojure

Updated
1 min read
Transpose a Matrix in Clojure

Imagine you have rows of letters, numbers, and Greek letters:

[[:a :b :c]
 [:1 :2 :3]
 [:alpha :beta :gamma]]

Now, imagine you want to transpose them:

(mapv vector [:a :b :c] [:1 :2 :3] [:alpha :beta :gamma])
;;=> [[:a :1 :alpha]
;;    [:b :2 :beta]
;;    [:c :3 :gamma]]

We don’t have to split them out of the containing vector thanks to the magic of apply:

(apply mapv vector [[:a :b :c] [:1 :2 :3] [:alpha :beta :gamma]])
;;=> [[:a :1 :alpha]
;;    [:b :2 :beta]
;;    [:c :3 :gamma]]

This is amazing.