'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 1:[1]

As of 2014, I would recommend using core.matrix for any numerical work in Clojure.

Among other things, this provides implementations of all the most common matrix operations:

(use 'clojure.core.matrix)

(transpose [[1 2] [3 4]])
=> [[1 3] [2 4]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mikera