English 中文(简体)
在肥料中,计算消化病媒平均数的有效方法是什么。
原标题:In clojure, what is an efficient way to calculate average of integer vectors

我已:

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

我想要平均这些(需要满足以下条件):

[3 6 5 5 6]

和MATLAB一样:

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

With Incan 我可以做到:

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

If data is rather large (and I have lots of them) is there a better way to do this?
Does it help to calculate the (count m) beforehand?
Does it help to defn the #(/ % (count m)) beforehand?

最佳回答

在不知道如何使用任何扫描器的情况下,你可以“从零开始”这样做。

(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)
问题回答

这里简单易行:

(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)




相关问题
How to improve Clojures error messages

I ve been playing a bit with Clojure and so far is fairly impressed, but one thing that I keep running into is wierd error messages from Clojure. This comes in two forms: Java errors, like null ...

clojure rmi classpath problem

I am trying to use clojure to implement a "plugin" for some vendor supplied software. Here is a little background on the vendor supplied software. It expects me to implement a particular interface ...

Help translating this Java codeblock to Clojure?

I m getting my feet wet with Clojure, and trying to get used to functional programming. I ve been translating various imperative functions from other languages into their Clojure equivalents -- and ...

Is functional Clojure or imperative Groovy more readable?

OK, no cheating now. No, really, take a minute or two and try this out. What does "positions" do? Edit: simplified according to cgrand s suggestion. (defn redux [[current next] flag] [(if flag ...

taking java method names as function arg in clojure

All, I want to create a function that takes a symbol representing a java method and applies it to some object: (user=> (defn f [m] (. "foo" (m))) When I execute this, I get a result much ...

how to efficiently apply a medium-weight function in parallel

I m looking to map a modestly-expensive function onto a large lazy seq in parallel. pmap is great but i m loosing to much to context switching. I think I need to increase the size of the chunk of work ...

热门标签