Prev Next

Uniform Random Matrix

Syntax
Matlab or Octave x = rand(mn)
C++ x = rand(mn)

Matlab or Octave
If m and n are integer scalars, the Matlab or Octave syntax
     
x = rand(mn)
sets x to an @(@ m \times n @)@ matrix each entry drawn from an independent uniform distribution on the interval @(@ [0,1] @)@.

Example
     function [ok] = rand_ok()
     ok      = true;
     m       = 2;
     n       = 3;
     % -------------------
     x       = rand(2, 3);
     % -------------------
     [m, n]  = size(x);
     ok      = ok & (m == 2);
     ok      = ok & (n == 3);
     ok      = ok & all( all( 0 < x ) );      % probability of limit case is zero
     ok      = ok & all( all( x < 1 ) );
     ok      = ok & all( x(1,:) ~= x(2,:) );  % probability of equality is zero
     return


C++
The following is a C++ implementation of the Matlab or Octave rand function with the syntax:
     
x = rand(mn)
where m and n are size_t values and x is an @(@ m \times n @)@ ublas matrix<double> object.

std::rand
If you want to use std::rand to generate the random values, you must first call the standard library function
     std::srand(
seed)
where seed is an unsigned int to initialize the random number generator.

mztuni
If there is a previous call of the form mztuni(seed) with seed > 1 , the mztuni random number generator will be used (instead of std::rand).

Example
     # include <mat2cpp.hpp>
     # include <cstdlib>
     
     bool rand_ok(void)
     {	bool   ok  = true;
     	using namespace mat2cpp;
     
     	size_t i, j, m(2), n(3);
     	// ---------------------------
     	matrix<double> x = rand(m, n);
     	// ---------------------------
     	ok &= (x.size1() == m);
     	ok &= (x.size2() == n);
     	for(i = 0; i < m; i++)
     	{	for(j = 0; j < n; j++)
     		{	ok &= (0. < x(i, j) ); // probability of limit is zero
     			ok &= (x(i, j) < 1.);
     		}
     	}
     	for(j = 0; j < n; j++)
     		ok &= (x(0, j) != x(1, j));    // probability zero
     	return ok;
     }


Source
The file rand.cpp contains the C++ source code for this operation.
Input File: omh/rand.omh