Search code examples
clojurematrix

Matrix transposition in clojure


In Clojure a possible representation of a matrix is a vector of vectors, i.e. [[1 2] [3 4]]. A possible implementation of transposing a matrix would be:

(defn transpose [matrix]
  (loop [matrix matrix, transp [], i 0]
    (if (< i (count (nth matrix 0)))
      (recur matrix 
             (conj transp
                   (vec (reduce concat
                                (map #(conj [] (nth %1 i))
                                     matrix))))
             (inc i))
      transp)))

Can anyone think of a more idiomatic Clojure implementation? For instance to avoid this horrid loop recur?


Solution

  • The usual solution is

    (defn transpose [m]
      (apply mapv vector m))