Method: NMatrix.random
- Defined in:
- lib/nmatrix/shortcuts.rb
.random(shape, opts = {}) ⇒ Object Also known as: rand
call-seq:
random(shape) -> NMatrix
Creates a :dense NMatrix with random numbers between 0 and 1 generated by Random::rand. The parameter is the dimension of the matrix.
If you use an integer dtype, make sure to specify :scale as a parameter, or you’ll only get a matrix of 0s.
-
Arguments :
-
shape-> Array (or integer for square matrix) specifying the dimensions.
-
-
Returns :
-
NMatrix filled with random values.
-
Examples:
NMatrix.random([2, 2]) # => 0.4859439730644226 0.1783195585012436
0.23193766176700592 0.4503345191478729
NMatrix.random([2, 2], :dtype => :byte, :scale => 255) # => [ [252, 108] [44, 12] ]
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/nmatrix/shortcuts.rb', line 370 def random(shape, opts={}) scale = opts.delete(:scale) || 1.0 rng = Random.new random_values = [] # Construct the values of the final matrix based on the dimension. if opts[:dtype] == :complex64 || opts[:dtype] == :complex128 NMatrix.size(shape).times { |i| random_values << Complex(rng.rand(scale), rng.rand(scale)) } else NMatrix.size(shape).times { |i| random_values << rng.rand(scale) } end NMatrix.new(shape, random_values, {:dtype => :float64, :stype => :dense}.merge(opts)) end |