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?
The usual solution is
(defn transpose [m] (apply mapv vector m))
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With