24
votes

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 to clojure implementation? for instance to avoid this horrid loop recur?

2
Do you know about incanter? If you need various matrix operations it could be a source of inspiration - github.com/liebke/incanter/wiki/matrices - sw1nn

2 Answers

68
votes

The usual solution is

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

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]]