Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix transposition in clojure

Tags:

matrix

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?

like image 316
kostas Avatar asked Apr 27 '12 08:04

kostas


2 Answers

The usual solution is

(defn transpose [m]   (apply mapv vector m)) 
like image 137
amalloy Avatar answered Sep 30 '22 20:09

amalloy


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]] 
like image 38
mikera Avatar answered Sep 30 '22 21:09

mikera