clojureclojure-contrib

Reshaping nested vectors


Given a nested vector A, which is the 3 x 4 matrix

[[1 4 7 10] [2 5 8 11] [3 6 9 12]]

Transform A such that the nested vector (matrix) is now 2 x 6.

The output would look like

[[1 3 5 7 9 11] [2 4 6 8 10 12]]

As of now I am stuck on the beginning implementation of this idea.


Solution

  • You might want to look into core.matrix:

    ;; using [net.mikera/core.matrix "0.18.0"] as a dependency
    (require '[clojure.core.matrix :as matrix])
    
    (-> [[1 4 7 10] [2 5 8 11] [3 6 9 12]]
      (matrix/transpose)
      (matrix/reshape [6 2])
      (matrix/transpose))
    ;= [[1 3 5 7 9 11] [2 4 6 8 10 12]]