Next: Famous Matrices, Previous: Rearranging Matrices, Up: Matrix Manipulation [Contents][Index]

### 16.3 Special Utility Matrices

eye (n)
eye (m, n)
eye ([m n])
eye (…, class)

  Return an identity matrix.

  If invoked with a single scalar argument n, return a square NxN identity matrix.

  If supplied two scalar arguments (m, n), `eye` takes them to be the number of rows and columns. If given a vector with two elements, `eye` uses the values of the elements as the number of rows and columns, respectively. For example:

      eye (3)
       ⇒  1  0  0
           0  1  0
           0  0  1

  The following expressions all produce the same result:

      eye (2)
      ≡
      eye (2, 2)
      ≡
      eye (size ([1, 2; 3, 4]))

  The optional argument class, allows `eye` to return an array of the specified type, like

      val = zeros (n,m, "uint8")

  Calling `eye` with no arguments is equivalent to calling it with an argument of 1. Any negative dimensions are treated as zero. These odd definitions are for compatibility with MATLAB.

  See also: speye, ones, zeros.

ones (n)
ones (m, n)
ones (m, n, k, …)
ones ([m n …])
ones (…, class)

  Return a matrix or N-dimensional array whose elements are all 1.

  If invoked with a single scalar integer argument n, return a square NxN matrix.

  If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with the given dimensions.

  To create a constant matrix whose values are all the same use an expression such as

      val_matrix = val * ones (m, n)

  The optional argument class specifies the class of the return array and defaults to double. For example:

      val = ones (m,n, "uint8")

  See also: zeros.

zeros (n)
zeros (m, n)
zeros (m, n, k, …)
zeros ([m n …])
zeros (…, class)

  Return a matrix or N-dimensional array whose elements are all 0.

  If invoked with a single scalar integer argument, return a square NxN matrix.

  If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with the given dimensions.

  The optional argument class specifies the class of the return array and defaults to double. For example:

      val = zeros (m,n, "uint8")

  See also: ones.

repmat (A, m)
repmat (A, m, n)
repmat (A, m, n, p …)
repmat (A, [m n])
repmat (A, [m n p …])

  Repeat matrix or N-D array.

  Form a block matrix of size m by n, with a copy of matrix A as each element.

  If n is not specified, form an m by m block matrix. For copying along more than two dimensions, specify the number of times to copy across each dimension m, n, p, …, in a vector in the second argument.

  See also: bsxfun, kron, repelems.

repelems (x, r)

  Construct a vector of repeated elements from x.

  r is a 2xN integer matrix specifying which elements to repeat and how often to repeat each element. Entries in the first row, r(1,j), select an element to repeat. The corresponding entry in the second row, r(2,j), specifies the repeat count. If x is a matrix then the columns of x are imagined to be stacked on top of each other for purposes of the selection index. A row vector is always returned.

  Conceptually the result is calculated as follows:

      y = [];
      for i = 1:columns (r)
        y = [y, x(r(1,i)*ones(1, r(2,i)))];
      endfor

  See also: repmat, cat.

xxx = repelem (x, R)
xxx = repelem (x, R_1, …, R_n)

  Construct an array of repeated elements from x and repeat instructions R_1, ….

  x must be a scalar, vector, or N-dimensional array.

  A repeat instruction R_j must either be a scalar or a vector. If the instruction is a scalar then each component of x in dimension j is repeated R_j times. If the instruction is a vector then it must have the same number of elements as the corresponding dimension j of x. In this case, the kth component of dimension j is repeated `R_j(k)` times.

  If x is a scalar or vector then `repelem` may be called with just a single repeat instruction R and `repelem` will return a vector with the same orientation as the input.

  If x is a matrix then at least two R_js must be specified.

  Note: Using `repelem` with a vector x and a vector for R_j is equivalent to Run Length Decoding.

  Examples:

      A = [1 2 3 4 5];
      B = [2 1 0 1 2];
      repelem (A, B)
        ⇒   1   1   2   4   5   5

      A = magic (3)
        ⇒   8   1   6
             3   5   7
             4   9   2
      B1 = [1 2 3];
      B2 = 2;
      repelem (A, B1, B2)
        ⇒     8   8   1   1   6   6
               3   3   5   5   7   7
               3   3   5   5   7   7
               4   4   9   9   2   2
               4   4   9   9   2   2
               4   4   9   9   2   2

  More R_j may be specified than the number of dimensions of x. Any excess R_j must be scalars (because x’s size in those dimensions is only 1), and x will be replicated in those dimensions accordingly.

      A = [1 2 3 4 5];
      B1 = 2;
      B2 = [2 1 3 0 2];
      B3 = 3;
      repelem (A, B1, B2, B3)
        ⇒    ans(:,:,1) =
                 1   1   2   3   3   3   5   5
                 1   1   2   3   3   3   5   5

              ans(:,:,2) =

                 1   1   2   3   3   3   5   5
                 1   1   2   3   3   3   5   5

              ans(:,:,3) =
                 1   1   2   3   3   3   5   5
                 1   1   2   3   3   3   5   5

  R_j must be specified in order. A placeholder of 1 may be used for dimensions which do not need replication.

      repelem ([-1, 0; 0, 1], 1, 2, 1, 2)
        ⇒  ans(:,:,1,1) =
              -1  -1   0   0
               0   0   1   1

            ans(:,:,1,2) =
              -1  -1   0   0
               0   0   1   1

  If fewer R_j are given than the number of dimensions in x, `repelem` will assume R_j is 1 for those dimensions.

      A = cat (3, [-1 0; 0 1], [-1 0; 0 1])
        ⇒  ans(:,:,1) =
              -1   0
               0   1

            ans(:,:,2) =
              -1   0
               0   1

      repelem (A,2,3)
        ⇒  ans(:,:,1) =
              -1  -1  -1   0   0   0
              -1  -1  -1   0   0   0
               0   0   0   1   1   1
               0   0   0   1   1   1

            ans(:,:,2) =
              -1  -1  -1   0   0   0
              -1  -1  -1   0   0   0
               0   0   0   1   1   1
               0   0   0   1   1   1

  `repelem` preserves the class of x, and works with strings, cell arrays, NA, and NAN inputs. If any R_j is 0 the output will be an empty array.

      repelem ("Octave", 2, 3)
        ⇒    OOOccctttaaavvveee
              OOOccctttaaavvveee

      repelem ([1 2 3; 1 2 3], 2, 0)
        ⇒    [](4x0)

  See also: cat, kron, repmat.

The functions `linspace` and `logspace` make it very easy to create vectors with evenly or logarithmically spaced elements. See Ranges.

linspace (start, end)
linspace (start, end, n)

  Return a row vector with n linearly spaced elements between start and end.

  If the number of elements is greater than one, then the endpoints start and end are always included in the range. If start is greater than end, the elements are stored in decreasing order. If the number of points is not specified, a value of 100 is used.

  The `linspace` function returns a row vector when both start and end are scalars. If one, or both, inputs are vectors, then `linspace` transforms them to column vectors and returns a matrix where each row is an independent sequence between `start(row_n), end(row_n)`.

  For compatibility with MATLAB, return the second argument (end) when only a single value (n = 1) is requested.

  See also: colon, logspace.

logspace (a, b)
logspace (a, b, n)
logspace (a, pi, n)

  Return a row vector with n elements logarithmically spaced from 10^a to 10^b.

  If n is unspecified it defaults to 50.

  If b is equal to pi, the points are between 10^a and pi, not 10^a and 10^pi, in order to be compatible with the corresponding MATLAB function.

  Also for compatibility with MATLAB, return the right-hand side of the range (10^b) when just a single value is requested.

  See also: linspace.

rand (n)
rand (m, n, …)
rand ([m n …])
v = rand ("state")
rand ("state", v)
rand ("state", "reset")
v = rand ("seed")
rand ("seed", v)
rand ("seed", "reset")
rand (…, "single")
rand (…, "double")

  Return a matrix with random elements uniformly distributed on the interval (0, 1).

  The arguments are handled the same as the arguments for `eye`.

  You can query the state of the random number generator using the form

      v = rand ("state")

  This returns a column vector v of length 625. Later, you can restore the random number generator to the state v using the form

      rand ("state", v)

  You may also initialize the state vector from an arbitrary vector of length ≤ 625 for v. This new state will be a hash based on the value of v, not v itself.

  By default, the generator is initialized from `/dev/urandom` if it is available, otherwise from CPU time, wall clock time, and the current fraction of a second. Note that this differs from MATLAB, which always initializes the state to the same state at startup. To obtain behavior comparable to MATLAB, initialize with a deterministic state vector in Octave’s startup files (see Startup Files).

  To compute the pseudo-random sequence, `rand` uses the Mersenne Twister with a period of 2^{19937}-1 (See M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator, ACM Trans. on Modeling and Computer Simulation Vol. 8, No. 1, pp. 3–30, January 1998, http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html). Do not use for cryptography without securely hashing several returned values together, otherwise the generator state can be learned after reading 624 consecutive values.

  Older versions of Octave used a different random number generator. The new generator is used by default as it is significantly faster than the old generator, and produces random numbers with a significantly longer cycle time. However, in some circumstances it might be desirable to obtain the same random sequences as produced by the old generators. To do this the keyword `"seed"` is used to specify that the old generators should be used, as in

      rand ("seed", val)

  which sets the seed of the generator to val. The seed of the generator can be queried with

      s = rand ("seed")

  However, it should be noted that querying the seed will not cause `rand` to use the old generators, only setting the seed will. To cause `rand` to once again use the new generators, the keyword `"state"` should be used to reset the state of the `rand`.

  The state or seed of the generator can be reset to a new random value using the `"reset"` keyword.

  The class of the value returned can be controlled by a trailing `"double"` or `"single"` argument. These are the only valid classes.

  See also: randn, rande, randg, randp.

randi (imax)
randi (imax, n)
randi (imax, m, n, …)
randi ([imin imax], …)
randi (…, "class")

  Return random integers in the range 1:imax.

  Additional arguments determine the shape of the return matrix. When no arguments are specified a single random integer is returned. If one argument n is specified then a square matrix (n x n) is returned. Two or more arguments will return a multi-dimensional matrix (m x n x …).

  The integer range may optionally be described by a two element matrix with a lower and upper bound in which case the returned integers will be on the interval [imin, imax].

  The optional argument class will return a matrix of the requested type. The default is `"double"`.

  The following example returns 150 integers in the range 1–10.

      ri = randi (10, 150, 1)

  Implementation Note: `randi` relies internally on `rand` which uses class `"double"` to represent numbers. This limits the maximum integer (imax) and range (imax - imin) to the value returned by the `flintmax` function. For IEEE floating point numbers this value is 2^{53} - 1.

  See also: rand.

randn (n)
randn (m, n, …)
randn ([m n …])
v = randn ("state")
randn ("state", v)
randn ("state", "reset")
v = randn ("seed")
randn ("seed", v)
randn ("seed", "reset")
randn (…, "single")
randn (…, "double")

  Return a matrix with normally distributed random elements having zero mean and variance one.

  The arguments are handled the same as the arguments for `rand`.

  By default, `randn` uses the Marsaglia and Tsang “Ziggurat technique” to transform from a uniform to a normal distribution.

  The class of the value returned can be controlled by a trailing `"double"` or `"single"` argument. These are the only valid classes.

  Reference: G. Marsaglia and W.W. Tsang, Ziggurat Method for Generating Random Variables, J. Statistical Software, vol 5, 2000, https://www.jstatsoft.org/v05/i08/

  See also: rand, rande, randg, randp.

rande (n)
rande (m, n, …)
rande ([m n …])
v = rande ("state")
rande ("state", v)
rande ("state", "reset")
v = rande ("seed")
rande ("seed", v)
rande ("seed", "reset")
rande (…, "single")
rande (…, "double")

  Return a matrix with exponentially distributed random elements.

  The arguments are handled the same as the arguments for `rand`.

  By default, `rande` uses the Marsaglia and Tsang “Ziggurat technique” to transform from a uniform to an exponential distribution.

  The class of the value returned can be controlled by a trailing `"double"` or `"single"` argument. These are the only valid classes.

  Reference: G. Marsaglia and W.W. Tsang, Ziggurat Method for Generating Random Variables, J. Statistical Software, vol 5, 2000, https://www.jstatsoft.org/v05/i08/

  See also: rand, randn, randg, randp.

randp (l, n)
randp (l, m, n, …)
randp (l, [m n …])
v = randp ("state")
randp ("state", v)
randp ("state", "reset")
v = randp ("seed")
randp ("seed", v)
randp ("seed", "reset")
randp (…, "single")
randp (…, "double")

  Return a matrix with Poisson distributed random elements with mean value parameter given by the first argument, l.

  The arguments are handled the same as the arguments for `rand`, except for the argument l.

  Five different algorithms are used depending on the range of l and whether or not l is a scalar or a matrix.

  For scalar l ≤ 12, use direct method.

    W.H. Press, et al., Numerical Recipes in C, Cambridge University Press, 1992.

  For scalar l > 12, use rejection method.[1]

    W.H. Press, et al., Numerical Recipes in C, Cambridge University Press, 1992.

  For matrix l ≤ 10, use inversion method.[2]

    E. Stadlober, et al., WinRand source code, available via FTP.

  For matrix l > 10, use patchwork rejection method.

    E. Stadlober, et al., WinRand source code, available via FTP, or H. Zechner, Efficient sampling from continuous and discrete unimodal distributions, Doctoral Dissertation, 156pp., Technical University Graz, Austria, 1994.

  For l > 1e8, use normal approximation.

    L. Montanet, et al., Review of Particle Properties, Physical Review D 50 p1284, 1994.

  The class of the value returned can be controlled by a trailing `"double"` or `"single"` argument. These are the only valid classes.

  See also: rand, randn, rande, randg.

randg (a, n)
randg (a, m, n, …)
randg (a, [m n …])
v = randg ("state")
randg ("state", v)
randg ("state", "reset")
v = randg ("seed")
randg ("seed", v)
randg ("seed", "reset")
randg (…, "single")
randg (…, "double")

  Return a matrix with `gamma (a,1)` distributed random elements.

  The arguments are handled the same as the arguments for `rand`, except for the argument a.

  This can be used to generate many distributions:

  `gamma (a, b)` for `a > -1`, `b > 0`

        r = b * randg (a)

  `beta (a, b)` for `a > -1`, `b > -1`

        r1 = randg (a, 1)
        r = r1 / (r1 + randg (b, 1))

  `Erlang (a, n)`

        r = a * randg (n)

  `chisq (df)` for `df > 0`

        r = 2 * randg (df / 2)

  `t (df)` for `0 < df < inf` (use randn if df is infinite)

        r = randn () / sqrt (2 * randg (df / 2) / df)

  `F (n1, n2)` for `0 < n1`, `0 < n2`

        ## r1 equals 1 if n1 is infinite
        r1 = 2 * randg (n1 / 2) / n1
        ## r2 equals 1 if n2 is infinite
        r2 = 2 * randg (n2 / 2) / n2
        r = r1 / r2

  negative `binomial (n, p)` for `n > 0`, `0 < p <= 1`

        r = randp ((1 - p) / p * randg (n))

  non-central `chisq (df, L)`, for `df >= 0` and `L > 0`

    (use chisq if `L = 0`)

        r = randp (L / 2)
        r(r > 0) = 2 * randg (r(r > 0))
        r(df > 0) += 2 * randg (df(df > 0)/2)

  `Dirichlet (a1, … ak)`

        r = (randg (a1), …, randg (ak))
        r = r / sum (r)

  The class of the value returned can be controlled by a trailing `"double"` or `"single"` argument. These are the only valid classes.

  See also: rand, randn, rande, randp.

The generators operate in the new or old style together, it is not possible to mix the two. Initializing any generator with `"state"` or `"seed"` causes the others to switch to the same style for future calls.

The state of each generator is independent and calls to different generators can be interleaved without affecting the final result. For example,

    rand ("state", [11, 22, 33]);
    randn ("state", [44, 55, 66]);
    u = rand (100, 1);
    n = randn (100, 1);

and

    rand ("state", [11, 22, 33]);
    randn ("state", [44, 55, 66]);
    u = zeros (100, 1);
    n = zeros (100, 1);
    for i = 1:100
      u(i) = rand ();
      n(i) = randn ();
    end

produce equivalent results. When the generators are initialized in the old style with `"seed"` only `rand` and `randn` are independent, because the old `rande`, `randg` and `randp` generators make calls to `rand` and `randn`.

The generators are initialized with random states at start-up, so that the sequences of random numbers are not the same each time you run Octave.7 If you really do need to reproduce a sequence of numbers exactly, you can set the state or seed to a specific value.

If invoked without arguments, `rand` and `randn` return a single element of a random sequence.

The original `rand` and `randn` functions use Fortran code from RANLIB, a library of Fortran routines for random number generation, compiled by Barry W. Brown and James Lovato of the Department of Biomathematics at The University of Texas, M.D. Anderson Cancer Center, Houston, TX 77030.

randperm (n)
randperm (n, m)

  Return a row vector containing a random permutation of `1:n`.

  If m is supplied, return m unique entries, sampled without replacement from `1:n`.

  The complexity is O(n) in memory and O(m) in time, unless m < n/5, in which case O(m) memory is used as well. The randomization is performed using rand(). All permutations are equally likely.

  See also: perms.

#### Footnotes

### (7)

The old versions of `rand` and `randn` obtain their initial seeds from the system clock.

Next: Famous Matrices, Previous: Rearranging Matrices, Up: Matrix Manipulation [Contents][Index]