1

假设我有一个 3x3 矩阵

(def myMatrix (matrix (range 9) 3))
; A 3x3 matrix
; -------------
; 0.00e+00  1.00e+00  2.00e+00 
; 3.00e+00  4.00e+00  5.00e+00 
; 6.00e+00  7.00e+00  8.00e+00 

我可以使用 $ 来获取一个元素,比如第二行第一列

($ 1 0 myMatrix) ; --> 3

是否有任何 API 方法可以快速更新元素然后返回矩阵?例如

(update-matrix-by-element 2 1 myMatrix 4)
; A 3x3 matrix
; -------------
; 0.00e+00  1.00e+00  2.00e+00 
; 4.00e+00  4.00e+00  5.00e+00 
; 6.00e+00  7.00e+00  8.00e+00 

我能找到的最接近的 API 方法是bind-rowsbind-columns,我当前使用这两种方法的函数版本是

;note i j starts from 1 rather than 0 
(defn update-matrix-by-element [i j myMatrix value]  
    (if (or (> i  (count (trans myMatrix))) (> j  (count  myMatrix)) (< i 1) (< j 1)  (not (integer? i)) (not (integer? j)))
      myMatrix
      (let [n (count myMatrix)
        m (count (trans myMatrix))
        rangeFn #(if (== %1 %2)  %1 (range %1  %2 ))
        m1 (if (==    (dec i) 0) []
             ($ (rangeFn 0 (dec i)) :all myMatrix))
        m2   (if (==  i  m) []
               ($ (rangeFn  i m)  :all myMatrix))
        matrixFn  #(if (matrix? % ) % [ %])
        newRow  (if (==   (dec j) 0) 
                  (bind-columns    [value]    (matrixFn ($  (dec i) (rangeFn   j   n ) myMatrix)))
                  (if (== j n )
                    (bind-columns  (matrixFn ($  (dec i) (rangeFn 0  (dec j) ) myMatrix))  [value]   )
                    (bind-columns  (matrixFn ($  (dec i) (rangeFn 0  (dec j) ) myMatrix))  [value]    (matrixFn ($   (dec i) (rangeFn   j    n ) myMatrix))))
                  )
    ]  

   ;  (prn " m1 " m1 ) (prn  " m2 " m2 ) (prn " newrow " newRow)

    (bind-rows m1 newRow m2))))
4

1 回答 1

2

如果您的意思是性能意义上的“快速”,那么您可能会查看core.matrix,它旨在支持快速可变矩阵运算。

使用vectorz-clj实现的示例core.matrix

(def M (matrix [[1 2] [3 4]]))
=> #<Matrix22 [[1.0,2.0][3.0,4.0]]>

(mset! M 0 0 10)
=> #<Matrix22 [[10.0,2.0][3.0,4.0]]>

(time (dotimes [i 1000000] (mset! M 0 0 i)))
"Elapsed time: 28.895842 msecs"   ;; i.e. < 30ns per mset! operation

这将比任何需要构建新的可变矩阵的方法都要快得多,尤其是当矩阵变得更大/具有更高的维度时

我正在努力core.matrix与 Incanter 巧妙地集成,因此不久之后您应该能够core.matrix在 Incanter 中透明地使用矩阵。

于 2013-04-15T04:08:26.133 回答