Note that there are some explanatory texts on larger screens.

plurals
  1. POWays to quickly update an element of a matrix in Incanter, Clojure?
    text
    copied!<p>Suppose I have a 3x3 matrix </p> <pre><code>(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 </code></pre> <p>I can use $ to get an element, say 2nd row 1st column </p> <pre><code>($ 1 0 myMatrix) ; --&gt; 3 </code></pre> <p>Is there any API method to quickly update an element and then return a matrix? e.g.</p> <pre><code>(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 </code></pre> <p>The closest API methods I can find are <a href="http://clojuredocs.org/incanter/incanter.core/bind-rows" rel="nofollow">bind-rows</a> and <a href="http://clojuredocs.org/incanter/incanter.core/bind-columns" rel="nofollow">bind-columns</a>, and my current version of function using these two methods is </p> <pre><code>;note i j starts from 1 rather than 0 (defn update-matrix-by-element [i j myMatrix value] (if (or (&gt; i (count (trans myMatrix))) (&gt; j (count myMatrix)) (&lt; i 1) (&lt; 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)))) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload