Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top