core.matrix: How to set all non-zero elements of an array to 1?

36 views
Skip to first unread message

Joachim De Beule

unread,
Nov 26, 2016, 10:58:03 AM11/26/16
to Numerical Clojure
What would be the best way to to set all non-zero elements of an array to 1 in core matrix?

For 1 dimensional arrays I figured this is a possibility, but I don't know if this is the best way to go:

(m/set-selection doc (m/non-zero-indices doc) 1.0)

For multi-dimensional arrays I could loop over all but one dimension and do something similar, but I'm guessing there should be more efficient ways?

Any advice is welcome!
Joachim

Mike Anderson

unread,
Dec 6, 2016, 11:21:15 PM12/6/16
to Numerical Clojure
I would probably use emap to do something something like:

(emap (fn [x] (if (zero? x) 0.0 1.0)) my-array)

emap is more likely to be optimised than something doing a lot of index manipulation, unless your array is very sparse.

Also if it is a mutable array then consider whether you want to change the array in-place or not (with emap! vs. emap)
Reply all
Reply to author
Forward
0 new messages