vincet
vincet

Reputation: 977

How to create a uniformly random matrix in Julia?

l want to get a matrix with uniformly random values sampled from [-1,2]

x= rand([-1,2],(3,3))
3x3 Array{Int64,2}:
 -1  -1  -1
  2  -1  -1
 -1  -1  -1

but it takes into consideration just -1 and 2, and I'm looking for continuous values for instance -0.9 , 0.75, -0.09, 1.80. How can I do that?

Upvotes: 8

Views: 13798

Answers (3)

isebarn
isebarn

Reputation: 3940

for random number in range [a,b]

rand() * (b-a) + a

and it works for a matrix aswell

rand(3,3) * (2 - (-1)) - 1
3x3 Array{Float64,2}:
 1.85611   0.456955   -0.0219579
 1.91196  -0.0352324   0.0296134
 1.63924  -0.567682    0.45602  

Upvotes: 11

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

You need to use a FloatRange{Float64} with the dessired step:

julia> rand(-1.0:0.01:2.0, 3, 3)
3x3 Array{Float64,2}:
 0.79  1.73   0.95
 0.73  1.4   -0.46
 1.42  1.68  -0.55

Upvotes: 5

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10980

Note: I am assuming here that you're looking for uniform random variables.

You can also use the Distributions package:

## Pkg.add("Distributions") # If you don't already have it installed.
using Distributions
rand(Uniform(-1,2), 3,3)

I do quite like isebarn's solution though, as it gets you thinking about the actual properties of the underlying probability distributions.

Upvotes: 17

Related Questions