In clojure, that is an efficient way to calculate the average number of integer vectors

I have:

(def data [[1 3 4 7 9] [7 6 3 2 7] [1 9 8 6 2]]) 

I want to average these (elementary):

 [3 6 5 5 6] 

As in MATLAB:

 mean([1 3 4 7 9; 7 6 3 2 7; 1 9 8 6 2]) 

Using Incanter, I can do:

 (map #(/ % (count m)) (apply plus data)) 

If the data is quite large (and I have a lot of them), is there a better way to do this?
Does this help to calculate (count m) in advance?
Does defn #(/ % (count m)) help in advance?

+6
source share
3 answers

Not knowing how to use any of the arsonists, here's how you could do it from scratch.

 (let [data [[1 3 4 7 9] [7 6 3 2 7] [1 9 8 6 2]] num (count data)] (apply map (fn [& items] (/ (apply + items) num)) data)) ;=> (3 6 5 5 6) 
+4
source

Here's a pretty clean and easy way to do this:

 (def data [[1 3 4 7 9] [7 6 3 2 7] [1 9 8 6 2]]) (defn average [coll] (/ (reduce + coll) (count coll))) (defn transpose [coll] (apply map vector coll)) (map average (transpose data)) => (3 6 5 5 6) 
+7
source

Since 2013, my recommendation has been to simply use core.matrix.stats to import all of these functions:

 (mean [[1 3 4 7 9] [7 6 3 2 7] [1 9 8 6 2]]) => [3.0 6.0 5.0 5.0 6.0] 

core.matrix.stats is based on the core.matrix API, so it will also work with other more optimized implementations of vectors and matrices - this would probably be a better option if you handle heavy matrix processing.

+6
source

Source: https://habr.com/ru/post/901964/


All Articles