Given a matrix as vector of vectors in clojure:
(def A [[1 2 3 4]
[5 6 7 8]
[9 10 11 12]
[13 14 15 16]])
I want to have it split into four quarters:
'([[1 2]
[5 6]] ; tl
[[3 4]
[7 8]] ; tr
[[9 10]
[13 14]] ; bl
[[11 12]
[15 16]]) ;br
The stupid approach goes like this (inspired by haskells submatrix):
(defn submatrix [A slice-col slice-row]
(let [tl (map (fn [col] (take slice-col col)) (take slice-row A))
tr (map (fn [col] (take slice-col col)) (drop slice-row A))
bl (map (fn [col] (drop slice-col col)) (take slice-row A))
br (map (fn [col] (drop slice-col col)) (drop slice-row A))]
(vector tl tr bl br))
)
This works (except that its based on lists instead of vectors) but is not very pretty in terms of functional programming.
Another approach that feels more natural with clojure but got me stuck:
;; just a helper, simmilar to split-at but returns vectors instead
(defn split-at' [idx v] [(subvec v 0 idx) (subvec v idx)])
(defn mquarter [A]
(let [cuts (map (fn [col] (split-at' 1 col)) A)] ; 1 is just for testing and will be a parameter later ...
(prn cuts) ; do something clever here like (map (fn [row] .. take .. drop ..) cuts)
))
If i call it e.g like (mquarter [[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15 16]])
it gives me ([[1] [2 3 4]] [[5] [6 7 8]] [[9] [10 11 12]] [[13] [14 15 16]])
. That is nice but i dont see how to merge the cuts into a new vector that has the expected structure.
Is there a clever clojure way to merge the cuts into the expected structure that contains my four quarters? The desired collection has quite a different structure than the input vector A
, so i wonder whether it's even possible to transform A
like this.
Note: I know there are libraries already doing this, i want to do it for the purpose of learning clojure.
Update: I did a quick performance comparison of the presented methods http://git.io/lAZ5OA with these result:
Elapsed time: 9.618612 msecs
Elapsed time: 8294.234684 msecs (is update-in that slow?)
Elapsed time: 4.223093 msecs by a-webb
Elapsed time: 8.166612 msecs
Elapsed time: 0.046654 msecs by andrew-myers (it is executed lazy right!?)
is not very pretty in terms of *functional programming*
?