1

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.

sunspots
  • 1,047
  • 13
  • 29
  • Are you looking to solve for any two matrices, one of dimension AxB and the other dimension CxD where A*B = C*D? Could take the component vectors of the first matrx and turn them into a single vector of length A*B, then partition the ranges of that long flat vector into a new matrix with C vectors of length D using "for"? – Levin Magruder Dec 27 '13 at 19:05
  • Yes, that is along the lines of what I am looking to do. i'm taking a look at how to partition the ranges now. – sunspots Dec 27 '13 at 19:09

2 Answers2

2

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]]
Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212
2

this function will reshape m to be composed of subvectors with the desired shape

(defn reshape [m & shape]
    (reduce (fn [vecs dim]
                (reduce #(conj %1 (subvec vecs %2 (+ dim %2)))
                        [] (range 0 (count vecs) dim)))
            (vec (flatten m)) (reverse shape)))

example:

(reshape [1 [2 3 4] 5 6 7 8] 2 2) => [[[1 2] [3 4]] [[5 6] [7 8]]]