在Clojure中就地更新矩阵 [英] Update matrix in-place in Clojure
问题描述
假设我有一个Clojure矩阵 A
这样(为清楚起见,格式化)
Suppose I have a Clojure matrix A
as such (formatted for clarity)
[[1 4 3]
[1 7 3]
[1 8 3]]
现在假设我要更新第一列的位置,通过eg将其乘以因子2,使得新矩阵变为
Now suppose I want to update the first column in place, by e.g. multiplying it by a factor of two, so that the new matrix becomes
[[2 4 3]
[2 2 3]
[2 8 3]]
如何在clojure中这样做?我已经尝试过 assoc
和像
How would one do this in clojure? I have tried things like assoc
and stuff like
(slice A 1 0)2)(select A [0 1 2] [2 3]))
自然不行。如果有像 assoc
的矩阵例如
Naturally that did not work. It would be great if there was something like assoc
for matrices e.g.
(massoc A [rows] [columns] replacement-vector)
c> numpy 在Python中:
or something simple like numpy
in Python:
A[:,0]*2 = [[2 4 3]
[2 2 3]
[2 8 3]]
感谢
推荐答案
您应该查看 clojure.core / matrix ,看看它是否支持这样的操作。
You should look into clojure.core/matrix and see if it supports operations like this.
这里可能是你正在寻找的东西。将 assoc
更改为新值而不是在应用函数后更新应该很简单。
Here is something that may be what you're looking for. It should be trivial to change this to assoc
a new value rather than updating after applying a function.
(defn mupdate-in
"Update all `coll' rows at `column' with `f'"
[coll column f & args]
(reduce #(apply update-in %1 [%2 column] f args)
coll
(range (count coll))))
例如:
(def m [[1 4 3]
[1 7 3]
[1 8 3]])
(mupdate-in m 0 * 2)
;; [[2 4 3]
;; [2 7 3]
;; [2 8 3]]
(mupdate-in m 2 + 10)
;; [[1 4 13]
;; [1 7 13]
;; [1 8 13]]
这篇关于在Clojure中就地更新矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!