I'm looking to build a function in Clojure that outputs m x n matrix of pseudorandom numbers drawn from the open interval (0,1). The specified inputs would be the row dimension m and column dimension n. I have familiarity with constructed matrices, nested vectors, in Clojure but have never generated random (psuedo) numbers before. My first guess, if starting from scratch, would use modular arithmetic to pump out inputs for the m x n matrix. Is this the easiest way to implement this idea?
Asked
Active
Viewed 157 times
1
-
1This is the first place I have asked. – sunspots Dec 26 '13 at 20:01
-
1It's a good question, but that seems like a violation of http://stackoverflow.com/questions/how-to-ask and commonsense use of search engines – clwhisk Dec 26 '13 at 20:04
-
The [Clojure cheatsheet](http://clojure.org/cheatsheet) is another good first-stop reference. – Shepmaster Dec 26 '13 at 20:06
-
If you decide that instead of a uniform distribution, you want something else, I would take a look to see what's available in Incanter. – Mars Dec 28 '13 at 06:47
2 Answers
4
The built-in (rand)
generates a number from the uniform between 0 and 1. So with:
(for [row (range m)]
(for [column (range n)]
(rand)))
there is no need to implement your own generator.

apai
- 489
- 4
- 8
2
Using core.matrix
, you can use the emap
function to do this:
(emap (fn [_] (rand)) (new-array [5 4]))
By default this returns a matrix of nested Clojure vectors, e.g.:
[[0.3325314113549507 0.7148578741930893 0.1786957191876699 0.46844096741466656]
[0.8216388560276083 0.3733963694778344 0.7311554209845575 0.05163744870109632]
[0.7838218008385947 0.8751976936581514 0.16056093051752107 0.5836745330219952]
[0.6137578842075752 0.9735681676917135 0.30319026184660314 0.19757184630153146]
[0.6216442815557222 0.795080498020428 0.685714719411497 0.1567460494112074]]

mikera
- 105,238
- 25
- 256
- 415