clojure.core.reducers/reduce with core.matrix.operators/+

59 views
Skip to first unread message

cej

unread,
Mar 1, 2015, 3:32:17 PM3/1/15
to numerica...@googlegroups.com
Hello,
  I am trying to figure out how to use clojure.core.reducers/reduce with core.matrix.operators/+.

Here is a little test example that I am thinking about:

(require '[clojure.core.reducers :as r])
(:refer-clojure :exclude [* - + == /])
(use '
clojure.core.matrix)
(use 'clojure.core.matrix.operators)

(def a [[1 2 3 4][1 -2 3 4][1 2 -3 4]])





core.matrix works here as this applies abs onto each element of each of the subvectors
 (->> a
     
(r/map abs)
     
(into []))


 
 This gives me the result that I want, but it creates a vector of vectors beforehand
(apply + (->> a
     
(r/map abs)
     
(into [])))


 
Something like this would be better; if it worked.      
(->> a
     
(r/map abs)
     
(r/reduce  +))

Is there away to do this?

Mike Anderson

unread,
Mar 1, 2015, 9:06:14 PM3/1/15
to numerica...@googlegroups.com
You should in general use "slices" if you want to get a sequence of the row vectors of a matrix. We can't guarantee that core.matrix arrays are reducible in general - it just happens to work if you use clojure vectors.

So you can do:

(->> (slices a)
        (r/map abs) 
        (r/reduce  +))

But note that you don't really even need reducers for this, since the following also works:

(->> (slices a)
        (map abs) 
        (reduce  +))

Also note that "abs" and "+" are the core.matrix versions here, i.e. they work on whole vectors at a time

cej

unread,
Mar 2, 2015, 10:33:03 AM3/2/15
to numerica...@googlegroups.com
After playing with this today, I realized I was being stupid, this works:

(->>  a
     
(r/map abs)
     
(r/reduce  + [0 0 0 0]))



Reply all
Reply to author
Forward
0 new messages