@c DO NOT EDIT!  Generated automatically by munge-texi.pl.

@c Copyright (C) 1996-2015 John W. Eaton
@c
@c This file is part of Octave.
@c
@c Octave is free software; you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by the
@c Free Software Foundation; either version 3 of the License, or (at
@c your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but WITHOUT
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
@c for more details.
@c
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <http://www.gnu.org/licenses/>.

@node Matrix Manipulation
@chapter Matrix Manipulation

There are a number of functions available for checking to see if the
elements of a matrix meet some condition, and for rearranging the
elements of a matrix.  For example, Octave can easily tell you if all
the elements of a matrix are finite, or are less than some specified
value.  Octave can also rotate the elements, extract the upper- or
lower-triangular parts, or sort the columns of a matrix.

@menu
* Finding Elements and Checking Conditions::
* Rearranging Matrices::
* Special Utility Matrices::
* Famous Matrices::
@end menu

@node Finding Elements and Checking Conditions
@section Finding Elements and Checking Conditions

The functions @code{any} and @code{all} are useful for determining
whether any or all of the elements of a matrix satisfy some condition.
The @code{find} function is also useful in determining which elements of
a matrix meet a specified condition.

@c any libinterp/corefcn/data.cc
@anchor{XREFany}
@deftypefn  {Built-in Function} {} any (@var{x})
@deftypefnx {Built-in Function} {} any (@var{x}, @var{dim})
For a vector argument, return true (logical 1) if any element of the vector
is nonzero.

For a matrix argument, return a row vector of logical ones and
zeros with each element indicating whether any of the elements of the
corresponding column of the matrix are nonzero.  For example:

@example
@group
any (eye (2, 4))
 @result{} [ 1, 1, 0, 0 ]
@end group
@end example

If the optional argument @var{dim} is supplied, work along dimension
@var{dim}.  For example:

@example
@group
any (eye (2, 4), 2)
 @result{} [ 1; 1 ]
@end group
@end example
@seealso{@ref{XREFall,,all}}
@end deftypefn


@c all libinterp/corefcn/data.cc
@anchor{XREFall}
@deftypefn  {Built-in Function} {} all (@var{x})
@deftypefnx {Built-in Function} {} all (@var{x}, @var{dim})
For a vector argument, return true (logical 1) if all elements of the vector
are nonzero.

For a matrix argument, return a row vector of logical ones and
zeros with each element indicating whether all of the elements of the
corresponding column of the matrix are nonzero.  For example:

@example
@group
all ([2, 3; 1, 0])
    @result{} [ 1, 0 ]
@end group
@end example

If the optional argument @var{dim} is supplied, work along dimension
@var{dim}.
@seealso{@ref{XREFany,,any}}
@end deftypefn


Since the comparison operators (@pxref{Comparison Ops}) return matrices
of ones and zeros, it is easy to test a matrix for many things, not just
whether the elements are nonzero.  For example,

@example
@group
all (all (rand (5) < 0.9))
     @result{} 0
@end group
@end example

@noindent
tests a random 5 by 5 matrix to see if all of its elements are less
than 0.9.

Note that in conditional contexts (like the test clause of @code{if} and
@code{while} statements) Octave treats the test as if you had typed
@code{all (all (condition))}.

@c xor scripts/miscellaneous/xor.m
@anchor{XREFxor}
@deftypefn  {Function File} {@var{z} =} xor (@var{x}, @var{y})
@deftypefnx {Function File} {@var{z} =} xor (@var{x1}, @var{x2}, @dots{})
Return the @dfn{exclusive or} of @var{x} and @var{y}.

For boolean expressions @var{x} and @var{y},
@code{xor (@var{x}, @var{y})} is true if and only if one of @var{x} or
@var{y} is true.  Otherwise, if @var{x} and @var{y} are both true or both
false, @code{xor} returns false.

The truth table for the xor operation is

@multitable @columnfractions 0.44 .03 .05 .03 0.44
@item @tab @var{x} @tab @var{y} @tab @var{z} @tab
@item @tab - @tab - @tab - @tab
@item @tab 0 @tab 0 @tab 0 @tab
@item @tab 1 @tab 0 @tab 1 @tab
@item @tab 0 @tab 1 @tab 1 @tab
@item @tab 1 @tab 1 @tab 0 @tab
@end multitable

If more than two arguments are given the xor operation is applied
cumulatively from left to right:

@example
(@dots{}((x1 XOR x2) XOR x3) XOR @dots{})
@end example

@seealso{@ref{XREFand,,and}, @ref{XREFor,,or}, @ref{XREFnot,,not}}
@end deftypefn


@c diff libinterp/corefcn/data.cc
@anchor{XREFdiff}
@deftypefn  {Built-in Function} {} diff (@var{x})
@deftypefnx {Built-in Function} {} diff (@var{x}, @var{k})
@deftypefnx {Built-in Function} {} diff (@var{x}, @var{k}, @var{dim})
If @var{x} is a vector of length @math{n}, @code{diff (@var{x})} is the
vector of first differences
@tex
 $x_2 - x_1, \ldots{}, x_n - x_{n-1}$.
@end tex
@ifnottex
 @var{x}(2) - @var{x}(1), @dots{}, @var{x}(n) - @var{x}(n-1).
@end ifnottex

If @var{x} is a matrix, @code{diff (@var{x})} is the matrix of column
differences along the first non-singleton dimension.

The second argument is optional.  If supplied, @code{diff (@var{x},
@var{k})}, where @var{k} is a non-negative integer, returns the
@var{k}-th differences.  It is possible that @var{k} is larger than
the first non-singleton dimension of the matrix.  In this case,
@code{diff} continues to take the differences along the next
non-singleton dimension.

The dimension along which to take the difference can be explicitly
stated with the optional variable @var{dim}.  In this case the
@var{k}-th order differences are calculated along this dimension.
In the case where @var{k} exceeds @code{size (@var{x}, @var{dim})}
an empty matrix is returned.
@seealso{@ref{XREFsort,,sort}, @ref{XREFmerge,,merge}}
@end deftypefn


@c isinf libinterp/corefcn/mappers.cc
@anchor{XREFisinf}
@deftypefn {Mapping Function} {} isinf (@var{x})
Return a logical array which is true where the elements of @var{x} are
are infinite and false where they are not.
For example:

@example
@group
isinf ([13, Inf, NA, NaN])
      @result{} [ 0, 1, 0, 0 ]
@end group
@end example
@seealso{@ref{XREFisfinite,,isfinite}, @ref{XREFisnan,,isnan}, @ref{XREFisna,,isna}}
@end deftypefn


@c isnan libinterp/corefcn/mappers.cc
@anchor{XREFisnan}
@deftypefn {Mapping Function} {} isnan (@var{x})
Return a logical array which is true where the elements of @var{x} are
NaN values and false where they are not.
NA values are also considered NaN values.  For example:

@example
@group
isnan ([13, Inf, NA, NaN])
      @result{} [ 0, 0, 1, 1 ]
@end group
@end example
@seealso{@ref{XREFisna,,isna}, @ref{XREFisinf,,isinf}, @ref{XREFisfinite,,isfinite}}
@end deftypefn


@c isfinite libinterp/corefcn/mappers.cc
@anchor{XREFisfinite}
@deftypefn {Mapping Function} {} isfinite (@var{x})
Return a logical array which is true where the elements of @var{x} are
finite values and false where they are not.

For example:

@example
@group
isfinite ([13, Inf, NA, NaN])
     @result{} [ 1, 0, 0, 0 ]
@end group
@end example
@seealso{@ref{XREFisinf,,isinf}, @ref{XREFisnan,,isnan}, @ref{XREFisna,,isna}}
@end deftypefn


@c common_size scripts/general/common_size.m
@anchor{XREFcommon_size}
@deftypefn {Function File} {[@var{err}, @var{y1}, @dots{}] =} common_size (@var{x1}, @dots{})
Determine if all input arguments are either scalar or of common
size.  If so, @var{err} is zero, and @var{yi} is a matrix of the
common size with all entries equal to @var{xi} if this is a scalar or
@var{xi} otherwise.  If the inputs cannot be brought to a common size,
@var{err} is 1, and @var{yi} is @var{xi}.  For example:

@example
@group
[errorcode, a, b] = common_size ([1 2; 3 4], 5)
     @result{} errorcode = 0
     @result{} a = [ 1, 2; 3, 4 ]
     @result{} b = [ 5, 5; 5, 5 ]
@end group
@end example

@noindent
This is useful for implementing functions where arguments can either
be scalars or of common size.
@end deftypefn


@c find libinterp/corefcn/find.cc
@anchor{XREFfind}
@deftypefn  {Built-in Function} {@var{idx} =} find (@var{x})
@deftypefnx {Built-in Function} {@var{idx} =} find (@var{x}, @var{n})
@deftypefnx {Built-in Function} {@var{idx} =} find (@var{x}, @var{n}, @var{direction})
@deftypefnx {Built-in Function} {[i, j] =} find (@dots{})
@deftypefnx {Built-in Function} {[i, j, v] =} find (@dots{})
Return a vector of indices of nonzero elements of a matrix, as a row if
@var{x} is a row vector or as a column otherwise.  To obtain a single index
for each matrix element, Octave pretends that the columns of a matrix form
one long vector (like Fortran arrays are stored).  For example:

@example
@group
find (eye (2))
  @result{} [ 1; 4 ]
@end group
@end example

If two outputs are requested, @code{find} returns the row and column
indices of nonzero elements of a matrix.  For example:

@example
@group
[i, j] = find (2 * eye (2))
    @result{} i = [ 1; 2 ]
    @result{} j = [ 1; 2 ]
@end group
@end example

If three outputs are requested, @code{find} also returns a vector
containing the nonzero values.  For example:

@example
@group
[i, j, v] = find (3 * eye (2))
       @result{} i = [ 1; 2 ]
       @result{} j = [ 1; 2 ]
       @result{} v = [ 3; 3 ]
@end group
@end example

If two inputs are given, @var{n} indicates the maximum number of
elements to find from the beginning of the matrix or vector.

If three inputs are given, @var{direction} should be one of
@qcode{"first"} or @qcode{"last"}, requesting only the first or last
@var{n} indices, respectively.  However, the indices are always returned in
ascending order.

Note that this function is particularly useful for sparse matrices, as
it extracts the nonzero elements as vectors, which can then be used to
create the original matrix.  For example:

@example
@group
sz = size (a);
[i, j, v] = find (a);
b = sparse (i, j, v, sz(1), sz(2));
@end group
@end example
@seealso{@ref{XREFnonzeros,,nonzeros}}
@end deftypefn


@c lookup libinterp/corefcn/lookup.cc
@anchor{XREFlookup}
@deftypefn  {Built-in Function} {@var{idx} =} lookup (@var{table}, @var{y})
@deftypefnx {Built-in Function} {@var{idx} =} lookup (@var{table}, @var{y}, @var{opt})
Lookup values in a sorted table.  Usually used as a prelude to
interpolation.

If table is increasing and @code{idx = lookup (table, y)}, then
@code{table(idx(i)) <= y(i) < table(idx(i+1))} for all @code{y(i)}
within the table.  If @code{y(i) < table(1)} then
@code{idx(i)} is 0. If @code{y(i) >= table(end)} or @code{isnan (y(i))} then
@code{idx(i)} is @code{n}.

If the table is decreasing, then the tests are reversed.
For non-strictly monotonic tables, empty intervals are always skipped.
The result is undefined if @var{table} is not monotonic, or if
@var{table} contains a NaN.

The complexity of the lookup is O(M*log(N)) where N is the size of
@var{table} and M is the size of @var{y}.  In the special case when @var{y}
is also sorted, the complexity is O(min(M*log(N),M+N)).

@var{table} and @var{y} can also be cell arrays of strings
(or @var{y} can be a single string).  In this case, string lookup
is performed using lexicographical comparison.

If @var{opts} is specified, it must be a string with letters indicating
additional options.

@table @code
@item m
@code{table(idx(i)) == val(i)} if @code{val(i)}
occurs in table; otherwise, @code{idx(i)} is zero.

@item b
@code{idx(i)} is a logical 1 or 0, indicating whether
@code{val(i)} is contained in table or not.

@item l
For numeric lookups
the leftmost subinterval shall be extended to infinity (i.e., all indices
at least 1)

@item r
For numeric lookups
the rightmost subinterval shall be extended to infinity (i.e., all indices
at most n-1).
@end table
@end deftypefn


If you wish to check if a variable exists at all, instead of properties
its elements may have, consult @ref{Status of Variables}.

@node Rearranging Matrices
@section Rearranging Matrices

@c fliplr scripts/general/fliplr.m
@anchor{XREFfliplr}
@deftypefn {Function File} {} fliplr (@var{x})
Flip array left to right.

Return a copy of @var{x} with the order of the columns reversed.  In
other words, @var{x} is flipped left-to-right about a vertical axis.  For
example:

@example
@group
fliplr ([1, 2; 3, 4])
     @result{}  2  1
         4  3
@end group
@end example

@seealso{@ref{XREFflipud,,flipud}, @ref{XREFflip,,flip}, @ref{XREFrot90,,rot90}, @ref{XREFrotdim,,rotdim}}
@end deftypefn


@c flipud scripts/general/flipud.m
@anchor{XREFflipud}
@deftypefn {Function File} {} flipud (@var{x})
Flip array upside down.

Return a copy of @var{x} with the order of the rows reversed.  In
other words, @var{x} is flipped upside-down about a horizontal axis.  For
example:

@example
@group
flipud ([1, 2; 3, 4])
     @result{}  3  4
         1  2
@end group
@end example

@seealso{@ref{XREFfliplr,,fliplr}, @ref{XREFflip,,flip}, @ref{XREFrot90,,rot90}, @ref{XREFrotdim,,rotdim}}
@end deftypefn


@c flip scripts/general/flip.m
@anchor{XREFflip}
@deftypefn  {Function File} {} flip (@var{x})
@deftypefnx {Function File} {} flip (@var{x}, @var{dim})
Flip array across specific dimension.

Return a copy of @var{x} flipped about the dimension @var{dim}.
@var{dim} defaults to the first non-singleton dimension.
For example:

@example
@group
flip ([1  2  3  4])
      @result{}  4  3  2  1

flip ([1; 2; 3; 4])
      @result{}  4
          3
          2
          1

flip ([1 2; 3 4])
      @result{}  3  4
          1  2

flip ([1 2; 3 4], 2)
      @result{}  2  1
          4  3
@end group
@end example

@seealso{@ref{XREFfliplr,,fliplr}, @ref{XREFflipud,,flipud}, @ref{XREFrot90,,rot90}, @ref{XREFrotdim,,rotdim}, @ref{XREFpermute,,permute}, @ref{XREFtranspose,,transpose}}
@end deftypefn


@c rot90 scripts/general/rot90.m
@anchor{XREFrot90}
@deftypefn  {Function File} {} rot90 (@var{A})
@deftypefnx {Function File} {} rot90 (@var{A}, @var{k})
Rotate array by 90 degree increments.

Return a copy of @var{A} with the elements rotated counterclockwise in
90-degree increments.  The second argument is optional, and specifies
how many 90-degree rotations are to be applied (the default value is 1).
Negative values of @var{k} rotate the matrix in a clockwise direction.
For example,

@example
@group
rot90 ([1, 2; 3, 4], -1)
    @result{}  3  1
        4  2
@end group
@end example

@noindent
rotates the given matrix clockwise by 90 degrees.  The following are all
equivalent statements:

@example
@group
rot90 ([1, 2; 3, 4], -1)
rot90 ([1, 2; 3, 4], 3)
rot90 ([1, 2; 3, 4], 7)
@end group
@end example

The rotation is always performed on the plane of the first two dimensions,
i.e., rows and columns.  To perform a rotation on any other plane, use
@code{rotdim}.

@seealso{@ref{XREFrotdim,,rotdim}, @ref{XREFfliplr,,fliplr}, @ref{XREFflipud,,flipud}, @ref{XREFflip,,flip}}
@end deftypefn


@c rotdim scripts/general/rotdim.m
@anchor{XREFrotdim}
@deftypefn  {Function File} {} rotdim (@var{x})
@deftypefnx {Function File} {} rotdim (@var{x}, @var{n})
@deftypefnx {Function File} {} rotdim (@var{x}, @var{n}, @var{plane})
Return a copy of @var{x} with the elements rotated counterclockwise in
90-degree increments.
The second argument @var{n} is optional, and specifies how many 90-degree
rotations are to be applied (the default value is 1).
The third argument is also optional and defines the plane of the
rotation.  If present, @var{plane} is a two element vector containing two
different valid dimensions of the matrix.  When @var{plane} is not given
the first two non-singleton dimensions are used.

Negative values of @var{n} rotate the matrix in a clockwise direction.
For example,

@example
@group
rotdim ([1, 2; 3, 4], -1, [1, 2])
     @result{}  3  1
         4  2
@end group
@end example

@noindent
rotates the given matrix clockwise by 90 degrees.  The following are all
equivalent statements:

@example
@group
rotdim ([1, 2; 3, 4], -1, [1, 2])
rotdim ([1, 2; 3, 4], 3, [1, 2])
rotdim ([1, 2; 3, 4], 7, [1, 2])
@end group
@end example
@seealso{@ref{XREFrot90,,rot90}, @ref{XREFfliplr,,fliplr}, @ref{XREFflipud,,flipud}, @ref{XREFflip,,flip}}
@end deftypefn


@c cat libinterp/corefcn/data.cc
@anchor{XREFcat}
@deftypefn {Built-in Function} {} cat (@var{dim}, @var{array1}, @var{array2}, @dots{}, @var{arrayN})
Return the concatenation of N-D array objects, @var{array1},
@var{array2}, @dots{}, @var{arrayN} along dimension @var{dim}.

@example
@group
A = ones (2, 2);
B = zeros (2, 2);
cat (2, A, B)
  @result{} 1 1 0 0
     1 1 0 0
@end group
@end example

Alternatively, we can concatenate @var{A} and @var{B} along the
second dimension in the following way:

@example
@group
[A, B]
@end group
@end example

@var{dim} can be larger than the dimensions of the N-D array objects
and the result will thus have @var{dim} dimensions as the
following example shows:

@example
@group
cat (4, ones (2, 2), zeros (2, 2))
  @result{} ans(:,:,1,1) =

       1 1
       1 1

     ans(:,:,1,2) =

       0 0
       0 0
@end group
@end example
@seealso{@ref{XREFhorzcat,,horzcat}, @ref{XREFvertcat,,vertcat}}
@end deftypefn


@c horzcat libinterp/corefcn/data.cc
@anchor{XREFhorzcat}
@deftypefn {Built-in Function} {} horzcat (@var{array1}, @var{array2}, @dots{}, @var{arrayN})
Return the horizontal concatenation of N-D array objects, @var{array1},
@var{array2}, @dots{}, @var{arrayN} along dimension 2.

Arrays may also be concatenated horizontally using the syntax for creating
new matrices.  For example:

@example
@var{hcat} = [ @var{array1}, @var{array2}, @dots{} ]
@end example
@seealso{@ref{XREFcat,,cat}, @ref{XREFvertcat,,vertcat}}
@end deftypefn


@c vertcat libinterp/corefcn/data.cc
@anchor{XREFvertcat}
@deftypefn {Built-in Function} {} vertcat (@var{array1}, @var{array2}, @dots{}, @var{arrayN})
Return the vertical concatenation of N-D array objects, @var{array1},
@var{array2}, @dots{}, @var{arrayN} along dimension 1.

Arrays may also be concatenated vertically using the syntax for creating
new matrices.  For example:

@example
@var{vcat} = [ @var{array1}; @var{array2}; @dots{} ]
@end example
@seealso{@ref{XREFcat,,cat}, @ref{XREFhorzcat,,horzcat}}
@end deftypefn


@c permute libinterp/corefcn/data.cc
@anchor{XREFpermute}
@deftypefn {Built-in Function} {} permute (@var{A}, @var{perm})
Return the generalized transpose for an N-D array object @var{A}.
The permutation vector @var{perm} must contain the elements
@code{1:ndims (A)} (in any order, but each element must appear only once).

The @var{N}th dimension of @var{A} gets remapped to dimension 
@code{@var{PERM}(@var{N})}.  For example:

@example
@group
@var{x} = zeros ([2, 3, 5, 7]);
size (@var{x})
   @result{}  2   3   5   7

size (permute (@var{x}, [2, 1, 3, 4]))
   @result{}  3   2   5   7

size (permute (@var{x}, [1, 3, 4, 2]))
   @result{}  2   5   7   3

## The identity permutation
size (permute (@var{x}, [1, 2, 3, 4]))
   @result{}  2   3   5   7
@end group
@end example
@seealso{@ref{XREFipermute,,ipermute}}
@end deftypefn


@c ipermute libinterp/corefcn/data.cc
@anchor{XREFipermute}
@deftypefn {Built-in Function} {} ipermute (@var{A}, @var{iperm})
The inverse of the @code{permute} function.  The expression

@example
ipermute (permute (A, perm), perm)
@end example

@noindent
returns the original array @var{A}.
@seealso{@ref{XREFpermute,,permute}}
@end deftypefn


@c reshape libinterp/corefcn/data.cc
@anchor{XREFreshape}
@deftypefn  {Built-in Function} {} reshape (@var{A}, @var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} reshape (@var{A}, [@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {} reshape (@var{A}, @dots{}, [], @dots{})
@deftypefnx {Built-in Function} {} reshape (@var{A}, @var{size})
Return a matrix with the specified dimensions (@var{m}, @var{n}, @dots{})
whose elements are taken from the matrix @var{A}.  The elements of the
matrix are accessed in column-major order (like Fortran arrays are stored).

The following code demonstrates reshaping a 1x4 row vector into a 2x2 square
matrix.

@example
@group
reshape ([1, 2, 3, 4], 2, 2)
      @result{}  1  3
          2  4
@end group
@end example

@noindent
Note that the total number of elements in the original
matrix (@code{prod (size (@var{A}))}) must match the total number of elements
in the new matrix (@code{prod ([@var{m} @var{n} @dots{}])}).

A single dimension of the return matrix may be left unspecified and Octave
will determine its size automatically.  An empty matrix ([]) is used to flag
the unspecified dimension.
@seealso{@ref{XREFresize,,resize}, @ref{XREFvec,,vec}, @ref{XREFpostpad,,postpad}, @ref{XREFcat,,cat}, @ref{XREFsqueeze,,squeeze}}
@end deftypefn


@c resize libinterp/corefcn/data.cc
@anchor{XREFresize}
@deftypefn  {Built-in Function} {} resize (@var{x}, @var{m})
@deftypefnx {Built-in Function} {} resize (@var{x}, @var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} resize (@var{x}, [@var{m} @var{n} @dots{}])
Resize @var{x} cutting off elements as necessary.

In the result, element with certain indices is equal to the corresponding
element of @var{x} if the indices are within the bounds of @var{x};
otherwise, the element is set to zero.

In other words, the statement

@example
y = resize (x, dv)
@end example

@noindent
is equivalent to the following code:

@example
@group
y = zeros (dv, class (x));
sz = min (dv, size (x));
for i = 1:length (sz)
  idx@{i@} = 1:sz(i);
endfor
y(idx@{:@}) = x(idx@{:@});
@end group
@end example

@noindent
but is performed more efficiently.

If only @var{m} is supplied, and it is a scalar, the dimension of the
result is @var{m}-by-@var{m}.
If @var{m}, @var{n}, @dots{} are all scalars, then the dimensions of
the result are @var{m}-by-@var{n}-by-@dots{}.
If given a vector as input, then the
dimensions of the result are given by the elements of that vector.

An object can be resized to more dimensions than it has;
in such case the missing dimensions are assumed to be 1.
Resizing an object to fewer dimensions is not possible.
@seealso{@ref{XREFreshape,,reshape}, @ref{XREFpostpad,,postpad}, @ref{XREFprepad,,prepad}, @ref{XREFcat,,cat}}
@end deftypefn


@c circshift scripts/general/circshift.m
@anchor{XREFcircshift}
@deftypefn {Function File} {@var{y} =} circshift (@var{x}, @var{n})
Circularly shift the values of the array @var{x}.  @var{n} must be
a vector of integers no longer than the number of dimensions in
@var{x}.  The values of @var{n} can be either positive or negative,
which determines the direction in which the values or @var{x} are
shifted.  If an element of @var{n} is zero, then the corresponding
dimension of @var{x} will not be shifted.  For example:

@example
@group
x = [1, 2, 3; 4, 5, 6; 7, 8, 9];
circshift (x, 1)
@result{}  7, 8, 9
    1, 2, 3
    4, 5, 6
circshift (x, -2)
@result{}  7, 8, 9
    1, 2, 3
    4, 5, 6
circshift (x, [0,1])
@result{}  3, 1, 2
    6, 4, 5
    9, 7, 8
@end group
@end example
@seealso{@ref{XREFpermute,,permute}, @ref{XREFipermute,,ipermute}, @ref{XREFshiftdim,,shiftdim}}
@end deftypefn


@c shift scripts/general/shift.m
@anchor{XREFshift}
@deftypefn  {Function File} {} shift (@var{x}, @var{b})
@deftypefnx {Function File} {} shift (@var{x}, @var{b}, @var{dim})
If @var{x} is a vector, perform a circular shift of length @var{b} of
the elements of @var{x}.

If @var{x} is a matrix, do the same for each column of @var{x}.
If the optional @var{dim} argument is given, operate along this
dimension.
@end deftypefn


@c shiftdim scripts/general/shiftdim.m
@anchor{XREFshiftdim}
@deftypefn  {Function File} {@var{y} =} shiftdim (@var{x}, @var{n})
@deftypefnx {Function File} {[@var{y}, @var{ns}] =} shiftdim (@var{x})
Shift the dimensions of @var{x} by @var{n}, where @var{n} must be
an integer scalar.  When @var{n} is positive, the dimensions of
@var{x} are shifted to the left, with the leading dimensions
circulated to the end.  If @var{n} is negative, then the dimensions
of @var{x} are shifted to the right, with @var{n} leading singleton
dimensions added.

Called with a single argument, @code{shiftdim}, removes the leading
singleton dimensions, returning the number of dimensions removed
in the second output argument @var{ns}.

For example:

@example
@group
x = ones (1, 2, 3);
size (shiftdim (x, -1))
   @result{} [1, 1, 2, 3]
size (shiftdim (x, 1))
   @result{} [2, 3]
[b, ns] = shiftdim (x)
   @result{} b = [1, 1, 1; 1, 1, 1]
   @result{} ns = 1
@end group
@end example
@seealso{@ref{XREFreshape,,reshape}, @ref{XREFpermute,,permute}, @ref{XREFipermute,,ipermute}, @ref{XREFcircshift,,circshift}, @ref{XREFsqueeze,,squeeze}}
@end deftypefn


@c sort libinterp/corefcn/data.cc
@anchor{XREFsort}
@deftypefn  {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x})
@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim})
@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{mode})
@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim}, @var{mode})
Return a copy of @var{x} with the elements arranged in increasing
order.  For matrices, @code{sort} orders the elements within columns

For example:

@example
@group
sort ([1, 2; 2, 3; 3, 1])
   @result{}  1  1
       2  2
       3  3
@end group
@end example

If the optional argument @var{dim} is given, then the matrix is sorted
along the dimension defined by @var{dim}.  The optional argument @code{mode}
defines the order in which the values will be sorted.  Valid values of
@code{mode} are @qcode{"ascend"} or @qcode{"descend"}.

The @code{sort} function may also be used to produce a matrix
containing the original row indices of the elements in the sorted
matrix.  For example:

@example
@group
[s, i] = sort ([1, 2; 2, 3; 3, 1])
  @result{} s = 1  1
         2  2
         3  3
  @result{} i = 1  3
         2  1
         3  2
@end group
@end example

For equal elements, the indices are such that equal elements are listed
in the order in which they appeared in the original list.

Sorting of complex entries is done first by magnitude (@code{abs (@var{z})})
and for any ties by phase angle (@code{angle (z)}).  For example:

@example
@group
sort ([1+i; 1; 1-i])
    @result{} 1 + 0i
       1 - 1i
       1 + 1i
@end group
@end example

NaN values are treated as being greater than any other value and are sorted
to the end of the list.

The @code{sort} function may also be used to sort strings and cell arrays
of strings, in which case ASCII dictionary order (uppercase 'A' precedes
lowercase 'a') of the strings is used.

The algorithm used in @code{sort} is optimized for the sorting of partially
ordered lists.
@seealso{@ref{XREFsortrows,,sortrows}, @ref{XREFissorted,,issorted}}
@end deftypefn


@c sortrows scripts/general/sortrows.m
@anchor{XREFsortrows}
@deftypefn  {Function File} {[@var{s}, @var{i}] =} sortrows (@var{A})
@deftypefnx {Function File} {[@var{s}, @var{i}] =} sortrows (@var{A}, @var{c})
Sort the rows of the matrix @var{A} according to the order of the
columns specified in @var{c}.  If @var{c} is omitted, a
lexicographical sort is used.  By default ascending order is used
however if elements of @var{c} are negative then the corresponding
column is sorted in descending order.
@seealso{@ref{XREFsort,,sort}}
@end deftypefn


@c issorted libinterp/corefcn/data.cc
@anchor{XREFissorted}
@deftypefn  {Built-in Function} {} issorted (@var{a})
@deftypefnx {Built-in Function} {} issorted (@var{a}, @var{mode})
@deftypefnx {Built-in Function} {} issorted (@var{a}, "rows", @var{mode})
Return true if the array is sorted according to @var{mode}, which
may be either @qcode{"ascending"}, @qcode{"descending"}, or
@qcode{"either"}.  By default,  @var{mode} is @qcode{"ascending"}.  NaNs
are treated in the same manner as @code{sort}.

If the optional argument @qcode{"rows"} is supplied, check whether
the array is sorted by rows as output by the function @code{sortrows}
(with no options).

This function does not support sparse matrices.
@seealso{@ref{XREFsort,,sort}, @ref{XREFsortrows,,sortrows}}
@end deftypefn



@c nth_element libinterp/corefcn/data.cc
@anchor{XREFnth_element}
@deftypefn  {Built-in Function} {} nth_element (@var{x}, @var{n})
@deftypefnx {Built-in Function} {} nth_element (@var{x}, @var{n}, @var{dim})
Select the n-th smallest element of a vector, using the ordering defined by
@code{sort}.  In other words, the result is equivalent to
@code{sort(@var{x})(@var{n})}.
@var{n} can also be a contiguous range, either ascending @code{l:u}
or descending @code{u:-1:l}, in which case a range of elements is returned.
If @var{x} is an array, @code{nth_element} operates along the dimension
defined by @var{dim}, or the first non-singleton dimension if @var{dim} is
not given.

nth_element encapsulates the C++ standard library algorithms nth_element and
partial_sort.  On average, the complexity of the operation is O(M*log(K)),
where @w{@code{M = size (@var{x}, @var{dim})}} and
@w{@code{K = length (@var{n})}}.
This function is intended for cases where the ratio K/M is small; otherwise,
it may be better to use @code{sort}.
@seealso{@ref{XREFsort,,sort}, @ref{XREFmin,,min}, @ref{XREFmax,,max}}
@end deftypefn


@anchor{XREFtriu}
@c tril libinterp/corefcn/tril.cc
@anchor{XREFtril}
@deftypefn  {Function File} {} tril (@var{A})
@deftypefnx {Function File} {} tril (@var{A}, @var{k})
@deftypefnx {Function File} {} tril (@var{A}, @var{k}, @var{pack})
@deftypefnx {Function File} {} triu (@var{A})
@deftypefnx {Function File} {} triu (@var{A}, @var{k})
@deftypefnx {Function File} {} triu (@var{A}, @var{k}, @var{pack})
Return a new matrix formed by extracting the lower (@code{tril})
or upper (@code{triu}) triangular part of the matrix @var{A}, and
setting all other elements to zero.  The second argument is optional,
and specifies how many diagonals above or below the main diagonal should
also be set to zero.

The default value of @var{k} is zero, so that @code{triu} and
@code{tril} normally include the main diagonal as part of the result.

If the value of @var{k} is nonzero integer, the selection of elements
starts at an offset of @var{k} diagonals above or below the main
diagonal; above for positive @var{k} and below for negative @var{k}.

The absolute value of @var{k} must not be greater than the number of
subdiagonals or superdiagonals.

For example:

@example
@group
tril (ones (3), -1)
     @result{}  0  0  0
         1  0  0
         1  1  0
@end group
@end example

@noindent
and

@example
@group
tril (ones (3), 1)
     @result{}  1  1  0
         1  1  1
         1  1  1
@end group
@end example

If the option @qcode{"pack"} is given as third argument, the extracted
elements are not inserted into a matrix, but rather stacked column-wise one
above other.
@seealso{@ref{XREFdiag,,diag}}
@end deftypefn


@c vec libinterp/corefcn/data.cc
@anchor{XREFvec}
@deftypefn  {Built-in Function} {@var{v} =} vec (@var{x})
@deftypefnx {Built-in Function} {@var{v} =} vec (@var{x}, @var{dim})
Return the vector obtained by stacking the columns of the matrix @var{x}
one above the other.  Without @var{dim} this is equivalent to
@code{@var{x}(:)}.  If @var{dim} is supplied, the dimensions of @var{v}
are set to @var{dim} with all elements along the last dimension.
This is equivalent to @code{shiftdim (@var{x}(:), 1-@var{dim})}.
@seealso{@ref{XREFvech,,vech}, @ref{XREFresize,,resize}, @ref{XREFcat,,cat}}
@end deftypefn


@c vech scripts/linear-algebra/vech.m
@anchor{XREFvech}
@deftypefn {Function File} {} vech (@var{x})
Return the vector obtained by eliminating all superdiagonal elements of
the square matrix @var{x} and stacking the result one column above the
other.  This has uses in matrix calculus where the underlying matrix
is symmetric and it would be pointless to keep values above the main
diagonal.
@seealso{@ref{XREFvec,,vec}}
@end deftypefn


@c prepad scripts/general/prepad.m
@anchor{XREFprepad}
@deftypefn  {Function File} {} prepad (@var{x}, @var{l})
@deftypefnx {Function File} {} prepad (@var{x}, @var{l}, @var{c})
@deftypefnx {Function File} {} prepad (@var{x}, @var{l}, @var{c}, @var{dim})
Prepend the scalar value @var{c} to the vector @var{x} until it is of length
@var{l}.  If @var{c} is not given, a value of 0 is used.

If @code{length (@var{x}) > @var{l}}, elements from the beginning of
@var{x} are removed until a vector of length @var{l} is obtained.

If @var{x} is a matrix, elements are prepended or removed from each row.

If the optional argument @var{dim} is given, operate along this
dimension.

If @var{dim} is larger than the dimensions of @var{x}, the result will
have @var{dim} dimensions.
@seealso{@ref{XREFpostpad,,postpad}, @ref{XREFcat,,cat}, @ref{XREFresize,,resize}}
@end deftypefn


@c postpad scripts/general/postpad.m
@anchor{XREFpostpad}
@deftypefn  {Function File} {} postpad (@var{x}, @var{l})
@deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c})
@deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim})
Append the scalar value @var{c} to the vector @var{x} until it is of length
@var{l}.  If @var{c} is not given, a value of 0 is used.

If @code{length (@var{x}) > @var{l}}, elements from the end of
@var{x} are removed until a vector of length @var{l} is obtained.

If @var{x} is a matrix, elements are appended or removed from each row.

If the optional argument @var{dim} is given, operate along this
dimension.

If @var{dim} is larger than the dimensions of @var{x}, the result will
have @var{dim} dimensions.
@seealso{@ref{XREFprepad,,prepad}, @ref{XREFcat,,cat}, @ref{XREFresize,,resize}}
@end deftypefn


@c diag libinterp/corefcn/data.cc
@anchor{XREFdiag}
@deftypefn  {Built-in Function} {@var{M} =} diag (@var{v})
@deftypefnx {Built-in Function} {@var{M} =} diag (@var{v}, @var{k})
@deftypefnx {Built-in Function} {@var{M} =} diag (@var{v}, @var{m}, @var{n})
@deftypefnx {Built-in Function} {@var{v} =} diag (@var{M})
@deftypefnx {Built-in Function} {@var{v} =} diag (@var{M}, @var{k})
Return a diagonal matrix with vector @var{v} on diagonal @var{k}.  The
second argument is optional.  If it is positive, the vector is placed on
the @var{k}-th superdiagonal.  If it is negative, it is placed on the
@var{-k}-th subdiagonal.  The default value of @var{k} is 0, and the
vector is placed on the main diagonal.  For example:

@example
@group
diag ([1, 2, 3], 1)
   @result{}  0  1  0  0
       0  0  2  0
       0  0  0  3
       0  0  0  0
@end group
@end example

@noindent
The 3-input form returns a diagonal matrix with vector @var{v} on the main
diagonal and the resulting matrix being of size @var{m} rows x @var{n}
columns.

Given a matrix argument, instead of a vector, @code{diag} extracts the
@var{k}-th diagonal of the matrix.
@end deftypefn


@c blkdiag scripts/general/blkdiag.m
@anchor{XREFblkdiag}
@deftypefn {Function File} {} blkdiag (@var{A}, @var{B}, @var{C}, @dots{})
Build a block diagonal matrix from @var{A}, @var{B}, @var{C}, @dots{}
All the arguments must be numeric and are two-dimensional matrices or
scalars.  If any argument is of type sparse, the output will also be
sparse.
@seealso{@ref{XREFdiag,,diag}, @ref{XREFhorzcat,,horzcat}, @ref{XREFvertcat,,vertcat}, @ref{XREFsparse,,sparse}}
@end deftypefn


@node Special Utility Matrices
@section Special Utility Matrices

@c eye libinterp/corefcn/data.cc
@anchor{XREFeye}
@deftypefn  {Built-in Function} {} eye (@var{n})
@deftypefnx {Built-in Function} {} eye (@var{m}, @var{n})
@deftypefnx {Built-in Function} {} eye ([@var{m} @var{n}])
@deftypefnx {Built-in Function} {} eye (@dots{}, @var{class})
Return an identity matrix.  If invoked with a single scalar argument @var{n},
return a square @nospell{NxN} identity matrix.  If
supplied two scalar arguments (@var{m}, @var{n}), @code{eye} takes them to be
the number of rows and columns.  If given a vector with two elements,
@code{eye} uses the values of the elements as the number of rows and columns,
respectively.  For example:

@example
@group
eye (3)
 @result{}  1  0  0
     0  1  0
     0  0  1
@end group
@end example

The following expressions all produce the same result:

@example
@group
eye (2)
@equiv{}
eye (2, 2)
@equiv{}
eye (size ([1, 2; 3, 4]))
@end group
@end example

The optional argument @var{class}, allows @code{eye} to return an array of
the specified type, like

@example
val = zeros (n,m, "uint8")
@end example

Calling @code{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 @sc{matlab}.
@seealso{@ref{XREFspeye,,speye}, @ref{XREFones,,ones}, @ref{XREFzeros,,zeros}}
@end deftypefn


@c ones libinterp/corefcn/data.cc
@anchor{XREFones}
@deftypefn  {Built-in Function} {} ones (@var{n})
@deftypefnx {Built-in Function} {} ones (@var{m}, @var{n})
@deftypefnx {Built-in Function} {} ones (@var{m}, @var{n}, @var{k}, @dots{})
@deftypefnx {Built-in Function} {} ones ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {} ones (@dots{}, @var{class})
Return a matrix or N-dimensional array whose elements are all 1.
If invoked with a single scalar integer argument @var{n}, return a square
@nospell{NxN} matrix.  If invoked with two or more scalar
integer arguments, or a vector of integer values, return an array with
the given dimensions.

If you need to create a matrix whose values are all the same, you should
use an expression like

@example
val_matrix = val * ones (m, n)
@end example

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

@example
val = ones (m,n, "uint8")
@end example
@seealso{@ref{XREFzeros,,zeros}}
@end deftypefn


@c zeros libinterp/corefcn/data.cc
@anchor{XREFzeros}
@deftypefn  {Built-in Function} {} zeros (@var{n})
@deftypefnx {Built-in Function} {} zeros (@var{m}, @var{n})
@deftypefnx {Built-in Function} {} zeros (@var{m}, @var{n}, @var{k}, @dots{})
@deftypefnx {Built-in Function} {} zeros ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {} zeros (@dots{}, @var{class})
Return a matrix or N-dimensional array whose elements are all 0.
If invoked with a single scalar integer argument, return a square
@nospell{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 @var{class} specifies the class of the return array
and defaults to double.  For example:

@example
val = zeros (m,n, "uint8")
@end example
@seealso{@ref{XREFones,,ones}}
@end deftypefn


@c repmat scripts/general/repmat.m
@anchor{XREFrepmat}
@deftypefn  {Function File} {} repmat (@var{A}, @var{m})
@deftypefnx {Function File} {} repmat (@var{A}, @var{m}, @var{n})
@deftypefnx {Function File} {} repmat (@var{A}, @var{m}, @var{n}, @var{p} @dots{})
@deftypefnx {Function File} {} repmat (@var{A}, [@var{m} @var{n}])
@deftypefnx {Function File} {} repmat (@var{A}, [@var{m} @var{n} @var{p} @dots{}])
Form a block matrix of size @var{m} by @var{n}, with a copy of matrix
@var{A} as each element.  If @var{n} is not specified, form an
@var{m} by @var{m} block matrix.  For copying along more than two
dimensions, specify the number of times to copy across each dimension
@var{m}, @var{n}, @var{p}, @dots{}, in a vector in the second argument.
@seealso{@ref{XREFrepelems,,repelems}}
@end deftypefn


@c repelems libinterp/corefcn/data.cc
@anchor{XREFrepelems}
@deftypefn {Built-in Function} {} repelems (@var{x}, @var{r})
Construct a vector of repeated elements from @var{x}.  @var{r}
is a 2x@var{N} integer matrix specifying which elements to repeat and
how often to repeat each element.

Entries in the first row, @var{r}(1,j), select an element to repeat.
The corresponding entry in the second row, @var{r}(2,j), specifies
the repeat count.  If @var{x} is a matrix then the columns of @var{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:

@example
@group
y = [];
for i = 1:columns (@var{r})
  y = [y, @var{x}(@var{r}(1,i)*ones(1, @var{r}(2,i)))];
endfor
@end group
@end example
@seealso{@ref{XREFrepmat,,repmat}, @ref{XREFcat,,cat}}
@end deftypefn


The functions @code{linspace} and @code{logspace} make it very easy to
create vectors with evenly or logarithmically spaced elements.
@xref{Ranges}.

@c linspace libinterp/corefcn/data.cc
@anchor{XREFlinspace}
@deftypefn  {Built-in Function} {} linspace (@var{base}, @var{limit})
@deftypefnx {Built-in Function} {} linspace (@var{base}, @var{limit}, @var{n})
Return a row vector with @var{n} linearly spaced elements between
@var{base} and @var{limit}.  If the number of elements is greater than one,
then the endpoints @var{base} and @var{limit} are always included in
the range.  If @var{base} is greater than @var{limit}, the elements are
stored in decreasing order.  If the number of points is not specified, a
value of 100 is used.

The @code{linspace} function always returns a row vector if both
@var{base} and @var{limit} are scalars.  If one, or both, of them are column
vectors, @code{linspace} returns a matrix.

For compatibility with @sc{matlab}, return the second argument (@var{limit})
if fewer than two values are requested.
@seealso{@ref{XREFlogspace,,logspace}}
@end deftypefn


@c logspace scripts/general/logspace.m
@anchor{XREFlogspace}
@deftypefn  {Function File} {} logspace (@var{a}, @var{b})
@deftypefnx {Function File} {} logspace (@var{a}, @var{b}, @var{n})
@deftypefnx {Function File} {} logspace (@var{a}, pi, @var{n})
Return a row vector with @var{n} elements logarithmically spaced from
@tex
$10^{a}$ to $10^{b}$.
@end tex
@ifnottex
10^@var{a} to 10^@var{b}.
@end ifnottex
If @var{n} is unspecified it defaults to 50.

If @var{b} is equal to
@tex
$\pi$,
@end tex
@ifnottex
pi,
@end ifnottex
the points are between
@tex
$10^{a}$ and $\pi$,
@end tex
@ifnottex
10^@var{a} and pi,
@end ifnottex
@emph{not}
@tex
$10^{a}$ and $10^{\pi}$,
@end tex
@ifnottex
10^@var{a} and 10^pi,
@end ifnottex
in order to be compatible with the corresponding @sc{matlab} function.

Also for compatibility with @sc{matlab}, return the second argument @var{b}
if fewer than two values are requested.
@seealso{@ref{XREFlinspace,,linspace}}
@end deftypefn


@c rand libinterp/corefcn/rand.cc
@anchor{XREFrand}
@deftypefn  {Built-in Function} {} rand (@var{n})
@deftypefnx {Built-in Function} {} rand (@var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} rand ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {@var{v} =} rand ("state")
@deftypefnx {Built-in Function} {} rand ("state", @var{v})
@deftypefnx {Built-in Function} {} rand ("state", "reset")
@deftypefnx {Built-in Function} {@var{v} =} rand ("seed")
@deftypefnx {Built-in Function} {} rand ("seed", @var{v})
@deftypefnx {Built-in Function} {} rand ("seed", "reset")
@deftypefnx {Built-in Function} {} rand (@dots{}, "single")
@deftypefnx {Built-in Function} {} rand (@dots{}, "double")
Return a matrix with random elements uniformly distributed on the
interval (0, 1).  The arguments are handled the same as the arguments
for @code{eye}.

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

@example
v = rand ("state")
@end example

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

@example
rand ("state", v)
@end example

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

By default, the generator is initialized from @code{/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 @sc{matlab}, which
always initializes the state to the same state at startup.  To obtain
behavior comparable to @sc{matlab}, initialize with a deterministic state
vector in Octave's startup files (@pxref{Startup Files}).

To compute the pseudo-random sequence, @code{rand} uses the Mersenne
Twister with a period of @math{2^{19937}-1} (See
@nospell{M. Matsumoto and T. Nishimura},
@cite{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,
@url{http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html}).
Do @strong{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 used by the old generators.  To do this the keyword
@qcode{"seed"} is used to specify that the old generators should be use,
as in

@example
rand ("seed", val)
@end example

@noindent
which sets the seed of the generator to @var{val}.  The seed of the
generator can be queried with

@example
s = rand ("seed")
@end example

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

The state or seed of the generator can be reset to a new random value
using the @qcode{"reset"} keyword.

The class of the value returned can be controlled by a trailing
@qcode{"double"} or @qcode{"single"} argument.  These are the only valid
classes.
@seealso{@ref{XREFrandn,,randn}, @ref{XREFrande,,rande}, @ref{XREFrandg,,randg}, @ref{XREFrandp,,randp}}
@end deftypefn


@c randi scripts/general/randi.m
@anchor{XREFrandi}
@deftypefn  {Function File} {} randi (@var{imax})
@deftypefnx {Function File} {} randi (@var{imax}, @var{n})
@deftypefnx {Function File} {} randi (@var{imax}, @var{m}, @var{n}, @dots{})
@deftypefnx {Function File} {} randi ([@var{imin} @var{imax}], @dots{})
@deftypefnx {Function File} {} randi (@dots{}, "@var{class}")
Return random integers in the range 1:@var{imax}.

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

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 @w{[@var{imin}, @var{imax}]}.

The optional argument @var{class} will return a matrix of the requested
type.  The default is @qcode{"double"}.

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

@example
ri = randi (10, 150, 1)
@end example

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

@seealso{@ref{XREFrand,,rand}}
@end deftypefn


@c randn libinterp/corefcn/rand.cc
@anchor{XREFrandn}
@deftypefn  {Built-in Function} {} randn (@var{n})
@deftypefnx {Built-in Function} {} randn (@var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} randn ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {@var{v} =} randn ("state")
@deftypefnx {Built-in Function} {} randn ("state", @var{v})
@deftypefnx {Built-in Function} {} randn ("state", "reset")
@deftypefnx {Built-in Function} {@var{v} =} randn ("seed")
@deftypefnx {Built-in Function} {} randn ("seed", @var{v})
@deftypefnx {Built-in Function} {} randn ("seed", "reset")
@deftypefnx {Built-in Function} {} randn (@dots{}, "single")
@deftypefnx {Built-in Function} {} randn (@dots{}, "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 @code{rand}.

By default, @code{randn} uses the @nospell{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
@qcode{"double"} or @qcode{"single"} argument.  These are the only valid
classes.

Reference: @nospell{G. Marsaglia and W.W. Tsang},
@cite{Ziggurat Method for Generating Random Variables},
J. Statistical Software, vol 5, 2000,
@url{http://www.jstatsoft.org/v05/i08/}

@seealso{@ref{XREFrand,,rand}, @ref{XREFrande,,rande}, @ref{XREFrandg,,randg}, @ref{XREFrandp,,randp}}
@end deftypefn


@c rande libinterp/corefcn/rand.cc
@anchor{XREFrande}
@deftypefn  {Built-in Function} {} rande (@var{n})
@deftypefnx {Built-in Function} {} rande (@var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} rande ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {@var{v} =} rande ("state")
@deftypefnx {Built-in Function} {} rande ("state", @var{v})
@deftypefnx {Built-in Function} {} rande ("state", "reset")
@deftypefnx {Built-in Function} {@var{v} =} rande ("seed")
@deftypefnx {Built-in Function} {} rande ("seed", @var{v})
@deftypefnx {Built-in Function} {} rande ("seed", "reset")
@deftypefnx {Built-in Function} {} rande (@dots{}, "single")
@deftypefnx {Built-in Function} {} rande (@dots{}, "double")
Return a matrix with exponentially distributed random elements.  The
arguments are handled the same as the arguments for @code{rand}.

By default, @code{randn} uses the @nospell{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
@qcode{"double"} or @qcode{"single"} argument.  These are the only valid
classes.

Reference: @nospell{G. Marsaglia and W.W. Tsang},
@cite{Ziggurat Method for Generating Random Variables},
J. Statistical Software, vol 5, 2000,
@url{http://www.jstatsoft.org/v05/i08/}

@seealso{@ref{XREFrand,,rand}, @ref{XREFrandn,,randn}, @ref{XREFrandg,,randg}, @ref{XREFrandp,,randp}}
@end deftypefn


@c randp libinterp/corefcn/rand.cc
@anchor{XREFrandp}
@deftypefn  {Built-in Function} {} randp (@var{l}, @var{n})
@deftypefnx {Built-in Function} {} randp (@var{l}, @var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} randp (@var{l}, [@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {@var{v} =} randp ("state")
@deftypefnx {Built-in Function} {} randp ("state", @var{v})
@deftypefnx {Built-in Function} {} randp ("state", "reset")
@deftypefnx {Built-in Function} {@var{v} =} randp ("seed")
@deftypefnx {Built-in Function} {} randp ("seed", @var{v})
@deftypefnx {Built-in Function} {} randp ("seed", "reset")
@deftypefnx {Built-in Function} {} randp (@dots{}, "single")
@deftypefnx {Built-in Function} {} randp (@dots{}, "double")
Return a matrix with Poisson distributed random elements with mean value
parameter given by the first argument, @var{l}.  The arguments
are handled the same as the arguments for @code{rand}, except for the
argument @var{l}.

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

@table @asis
@item For scalar @var{l} @leq{} 12, use direct method.
W.H. Press, et al., @cite{Numerical Recipes in C},
Cambridge University Press, 1992.

@item For scalar @var{l} > 12, use rejection method.[1]
W.H. Press, et al., @cite{Numerical Recipes in C},
Cambridge University Press, 1992.

@item For matrix @var{l} @leq{} 10, use inversion method.[2]
@nospell{E. Stadlober, et al., WinRand source code}, available via FTP.

@item For matrix @var{l} > 10, use patchwork rejection method.
@nospell{E. Stadlober, et al., WinRand source code}, available via FTP, or
@nospell{H. Zechner}, @cite{Efficient sampling from continuous and discrete
unimodal distributions}, Doctoral Dissertation, 156pp., Technical
University @nospell{Graz}, Austria, 1994.

@item For @var{l} > 1e8, use normal approximation.
@nospell{L. Montanet}, et al., @cite{Review of Particle Properties},
Physical Review D 50 p1284, 1994.
@end table

The class of the value returned can be controlled by a trailing
@qcode{"double"} or @qcode{"single"} argument.  These are the only valid
classes.
@seealso{@ref{XREFrand,,rand}, @ref{XREFrandn,,randn}, @ref{XREFrande,,rande}, @ref{XREFrandg,,randg}}
@end deftypefn


@c randg libinterp/corefcn/rand.cc
@anchor{XREFrandg}
@deftypefn  {Built-in Function} {} randg (@var{n})
@deftypefnx {Built-in Function} {} randg (@var{m}, @var{n}, @dots{})
@deftypefnx {Built-in Function} {} randg ([@var{m} @var{n} @dots{}])
@deftypefnx {Built-in Function} {@var{v} =} randg ("state")
@deftypefnx {Built-in Function} {} randg ("state", @var{v})
@deftypefnx {Built-in Function} {} randg ("state", "reset")
@deftypefnx {Built-in Function} {@var{v} =} randg ("seed")
@deftypefnx {Built-in Function} {} randg ("seed", @var{v})
@deftypefnx {Built-in Function} {} randg ("seed", "reset")
@deftypefnx {Built-in Function} {} randg (@dots{}, "single")
@deftypefnx {Built-in Function} {} randg (@dots{}, "double")
Return a matrix with @code{gamma (@var{a},1)} distributed random elements.
The arguments are handled the same as the arguments for @code{rand},
except for the argument @var{a}.

This can be used to generate many distributions:

@table @asis
@item @code{gamma (a, b)} for @code{a > -1}, @code{b > 0}

@example
r = b * randg (a)
@end example

@item @code{beta (a, b)} for @code{a > -1}, @code{b > -1}

@example
@group
r1 = randg (a, 1)
r = r1 / (r1 + randg (b, 1))
@end group
@end example

@item @code{Erlang (a, n)}

@example
r = a * randg (n)
@end example

@item @code{chisq (df)} for @code{df > 0}

@example
r = 2 * randg (df / 2)
@end example

@item @code{t (df)} for @code{0 < df < inf} (use randn if df is infinite)

@example
r = randn () / sqrt (2 * randg (df / 2) / df)
@end example

@item @code{F (n1, n2)} for @code{0 < n1}, @code{0 < n2}

@example
@group
## 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

@end group
@end example

@item negative @code{binomial (n, p)} for @code{n > 0}, @code{0 < p <= 1}

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

@item non-central @code{chisq (df, L)}, for @code{df >= 0} and @code{L > 0}
(use chisq if @code{L = 0})

@example
@group
r = randp (L / 2)
r(r > 0) = 2 * randg (r(r > 0))
r(df > 0) += 2 * randg (df(df > 0)/2)
@end group
@end example

@item @code{Dirichlet (a1, @dots{} ak)}

@example
@group
r = (randg (a1), @dots{}, randg (ak))
r = r / sum (r)
@end group
@end example

@end table

The class of the value returned can be controlled by a trailing
@qcode{"double"} or @qcode{"single"} argument.  These are the only valid
classes.
@seealso{@ref{XREFrand,,rand}, @ref{XREFrandn,,randn}, @ref{XREFrande,,rande}, @ref{XREFrandp,,randp}}
@end deftypefn


The generators operate in the new or old style together, it is not
possible to mix the two.  Initializing any generator with
@qcode{"state"} or @qcode{"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,

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

@noindent
and

@example
@group
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
@end group
@end example

@noindent
produce equivalent results.  When the generators are initialized in
the old style with @qcode{"seed"} only @code{rand} and @code{randn} are
independent, because the old @code{rande}, @code{randg} and
@code{randp} generators make calls to @code{rand} and @code{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.@footnote{The old versions of @code{rand} and @code{randn}
obtain their initial seeds from the system clock.} 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, @code{rand} and @code{randn} return a
single element of a random sequence.

The original @code{rand} and @code{randn} functions use Fortran code from
@sc{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.

@c randperm libinterp/corefcn/rand.cc
@anchor{XREFrandperm}
@deftypefn  {Built-in Function} {} randperm (@var{n})
@deftypefnx {Built-in Function} {} randperm (@var{n}, @var{m})
Return a row vector containing a random permutation of @code{1:@var{n}}.
If @var{m} is supplied, return @var{m} unique entries, sampled without
replacement from @code{1:@var{n}}.  The complexity is O(@var{n}) in
memory and O(@var{m}) in time, unless @var{m} < @var{n}/5, in which case
O(@var{m}) memory is used as well.  The randomization is performed using
rand().  All permutations are equally likely.
@seealso{@ref{XREFperms,,perms}}
@end deftypefn


@node Famous Matrices
@section Famous Matrices

The following functions return famous matrix forms.

@c gallery scripts/special-matrix/gallery.m
@anchor{XREFgallery}
@deftypefn  {Function File} {} gallery (@var{name})
@deftypefnx {Function File} {} gallery (@var{name}, @var{args})
Create interesting matrices for testing.

@end deftypefn

@deftypefn  {Function File} {@var{c} =} gallery ("cauchy", @var{x})
@deftypefnx {Function File} {@var{c} =} gallery ("cauchy", @var{x}, @var{y})
Create a Cauchy matrix.

@end deftypefn

@deftypefn  {Function File} {@var{c} =} gallery ("chebspec", @var{n})
@deftypefnx {Function File} {@var{c} =} gallery ("chebspec", @var{n}, @var{k})
Create a Chebyshev spectral differentiation matrix.

@end deftypefn

@deftypefn  {Function File} {@var{c} =} gallery ("chebvand", @var{p})
@deftypefnx {Function File} {@var{c} =} gallery ("chebvand", @var{m}, @var{p})
Create a Vandermonde-like matrix for the Chebyshev polynomials.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("chow", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("chow", @var{n}, @var{alpha})
@deftypefnx {Function File} {@var{a} =} gallery ("chow", @var{n}, @var{alpha}, @var{delta})
Create a Chow matrix -- a singular Toeplitz lower Hessenberg matrix.

@end deftypefn

@deftypefn {Function File} {@var{c} =} gallery ("circul", @var{v})
Create a circulant matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("clement", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("clement", @var{n}, @var{k})
Create a tridiagonal matrix with zero diagonal entries.

@end deftypefn

@deftypefn  {Function File} {@var{c} =} gallery ("compar", @var{a})
@deftypefnx {Function File} {@var{c} =} gallery ("compar", @var{a}, @var{k})
Create a comparison matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("condex", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("condex", @var{n}, @var{k})
@deftypefnx {Function File} {@var{a} =} gallery ("condex", @var{n}, @var{k}, @var{theta})
Create a `counterexample' matrix to a condition estimator.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("cycol", [@var{m} @var{n}])
@deftypefnx {Function File} {@var{a} =} gallery ("cycol", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery (@dots{}, @var{k})
Create a matrix whose columns repeat cyclically.

@end deftypefn

@deftypefn  {Function File} {[@var{c}, @var{d}, @var{e}] =} gallery ("dorr", @var{n})
@deftypefnx {Function File} {[@var{c}, @var{d}, @var{e}] =} gallery ("dorr", @var{n}, @var{theta})
@deftypefnx {Function File} {@var{a} =} gallery ("dorr", @dots{})
Create a diagonally dominant, ill-conditioned, tridiagonal matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("dramadah", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("dramadah", @var{n}, @var{k})
Create a (0, 1) matrix whose inverse has large integer entries.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("fiedler", @var{c})
Create a symmetric @nospell{Fiedler} matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("forsythe", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("forsythe", @var{n}, @var{alpha})
@deftypefnx {Function File} {@var{a} =} gallery ("forsythe", @var{n}, @var{alpha}, @var{lambda})
Create a @nospell{Forsythe} matrix (a perturbed Jordan block).

@end deftypefn

@deftypefn  {Function File} {@var{f} =} gallery ("frank", @var{n})
@deftypefnx {Function File} {@var{f} =} gallery ("frank", @var{n}, @var{k})
Create a Frank matrix (ill-conditioned eigenvalues).

@end deftypefn

@deftypefn {Function File} {@var{c} =} gallery ("gcdmat", @var{n})
Create a greatest common divisor matrix.

@var{c} is an @var{n}-by-@var{n} matrix whose values correspond to the
greatest common divisor of its coordinate values, i.e., @var{c}(i,j)
correspond @code{gcd (i, j)}.
@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("gearmat", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("gearmat", @var{n}, @var{i})
@deftypefnx {Function File} {@var{a} =} gallery ("gearmat", @var{n}, @var{i}, @var{j})
Create a Gear matrix.

@end deftypefn

@deftypefn  {Function File} {@var{g} =} gallery ("grcar", @var{n})
@deftypefnx {Function File} {@var{g} =} gallery ("grcar", @var{n}, @var{k})
Create a Toeplitz matrix with sensitive eigenvalues.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("hanowa", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("hanowa", @var{n}, @var{d})
Create a matrix whose eigenvalues lie on a vertical line in the complex
plane.

@end deftypefn

@deftypefn  {Function File} {@var{v} =} gallery ("house", @var{x})
@deftypefnx {Function File} {[@var{v}, @var{beta}] =} gallery ("house", @var{x})
Create a householder matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("integerdata", @var{imax}, [@var{M} @var{N} @dots{}], @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("integerdata", @var{imax}, @var{M}, @var{N}, @dots{}, @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("integerdata", [@var{imin}, @var{imax}], [@var{M} @var{N} @dots{}], @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("integerdata", [@var{imin}, @var{imax}], @var{M}, @var{N}, @dots{}, @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("integerdata", @dots{}, "@var{class}")
Create a matrix with random integers in the range [1, @var{imax}].
If @var{imin} is given then the integers are in the range
[@var{imin}, @var{imax}].

The second input is a matrix of dimensions describing the size of the output.
The dimensions can also be input as comma-separated arguments.

The input @var{j} is an integer index in the range [0, 2^32-1].  The
values of the output matrix are always exactly the same
(reproducibility) for a given size input and @var{j} index.

The final optional argument determines the class of the resulting matrix.
Possible values for @var{class}: @qcode{"uint8"}, @qcode{"uint16"},
@qcode{"uint32"}, @qcode{"int8"}, @qcode{"int16"}, int32", @qcode{"single"},
@qcode{"double"}.  The default is @qcode{"double"}.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("invhess", @var{x})
@deftypefnx {Function File} {@var{a} =} gallery ("invhess", @var{x}, @var{y})
Create the inverse of an upper Hessenberg matrix.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("invol", @var{n})
Create an involutory matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("ipjfact", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("ipjfact", @var{n}, @var{k})
Create an Hankel matrix with factorial elements.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("jordbloc", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("jordbloc", @var{n}, @var{lambda})
Create a Jordan block.

@end deftypefn

@deftypefn  {Function File} {@var{u} =} gallery ("kahan", @var{n})
@deftypefnx {Function File} {@var{u} =} gallery ("kahan", @var{n}, @var{theta})
@deftypefnx {Function File} {@var{u} =} gallery ("kahan", @var{n}, @var{theta}, @var{pert})
Create a @nospell{Kahan} matrix (upper trapezoidal).

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("kms", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("kms", @var{n}, @var{rho})
Create a @nospell{Kac-Murdock-Szego} Toeplitz matrix.

@end deftypefn

@deftypefn  {Function File} {@var{b} =} gallery ("krylov", @var{a})
@deftypefnx {Function File} {@var{b} =} gallery ("krylov", @var{a}, @var{x})
@deftypefnx {Function File} {@var{b} =} gallery ("krylov", @var{a}, @var{x}, @var{j})
Create a Krylov matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("lauchli", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("lauchli", @var{n}, @var{mu})
Create a @nospell{Lauchli} matrix (rectangular).

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("lehmer", @var{n})
Create a @nospell{Lehmer} matrix (symmetric positive definite).

@end deftypefn

@deftypefn {Function File} {@var{t} =} gallery ("lesp", @var{n})
Create a tridiagonal matrix with real, sensitive eigenvalues.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("lotkin", @var{n})
Create a @nospell{Lotkin} matrix.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("minij", @var{n})
Create a symmetric positive definite matrix MIN(i,j).

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("moler", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("moler", @var{n}, @var{alpha})
Create a @nospell{Moler} matrix (symmetric positive definite).

@end deftypefn

@deftypefn {Function File} {[@var{a}, @var{t}] =} gallery ("neumann", @var{n})
Create a singular matrix from the discrete Neumann problem (sparse).

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("normaldata", [@var{M} @var{N} @dots{}], @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("normaldata", @var{M}, @var{N}, @dots{}, @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("normaldata", @dots{}, "@var{class}")
Create a matrix with random samples from the standard normal distribution
(mean = 0, std = 1).

The first input is a matrix of dimensions describing the size of the output.
The dimensions can also be input as comma-separated arguments.

The input @var{j} is an integer index in the range [0, 2^32-1].  The
values of the output matrix are always exactly the same
(reproducibility) for a given size input and @var{j} index.

The final optional argument determines the class of the resulting matrix.
Possible values for @var{class}: @qcode{"single"}, @qcode{"double"}.
The default is @qcode{"double"}.

@end deftypefn

@deftypefn  {Function File} {@var{q} =} gallery ("orthog", @var{n})
@deftypefnx {Function File} {@var{q} =} gallery ("orthog", @var{n}, @var{k})
Create orthogonal and nearly orthogonal matrices.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("parter", @var{n})
Create a @nospell{Parter} matrix (a Toeplitz matrix with singular values
near pi).

@end deftypefn

@deftypefn  {Function File} {@var{p} =} gallery ("pei", @var{n})
@deftypefnx {Function File} {@var{p} =} gallery ("pei", @var{n}, @var{alpha})
Create a Pei matrix.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("Poisson", @var{n})
Create a block tridiagonal matrix from Poisson's equation (sparse).

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("prolate", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("prolate", @var{n}, @var{w})
Create a prolate matrix (symmetric, ill-conditioned Toeplitz matrix).

@end deftypefn

@deftypefn {Function File} {@var{h} =} gallery ("randhess", @var{x})
Create a random, orthogonal upper Hessenberg matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("rando", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("rando", @var{n}, @var{k})
Create a random matrix with elements -1, 0 or 1.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("randsvd", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa})
@deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode})
@deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode}, @var{kl})
@deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode}, @var{kl}, @var{ku})
Create a random matrix with pre-assigned singular values.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("redheff", @var{n})
Create a zero and ones matrix of @nospell{Redheffer} associated with the
Riemann hypothesis.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("riemann", @var{n})
Create a matrix associated with the Riemann hypothesis.

@end deftypefn

@deftypefn {Function File} {@var{a} =} gallery ("ris", @var{n})
Create a symmetric Hankel matrix.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("smoke", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("smoke", @var{n}, @var{k})
Create a complex matrix, with a `smoke ring' pseudospectrum.

@end deftypefn

@deftypefn  {Function File} {@var{t} =} gallery ("toeppd", @var{n})
@deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m})
@deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m}, @var{w})
@deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m}, @var{w}, @var{theta})
Create a symmetric positive definite Toeplitz matrix.

@end deftypefn

@deftypefn  {Function File} {@var{p} =} gallery ("toeppen", @var{n})
@deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a})
@deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b})
@deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c})
@deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c}, @var{d})
@deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c}, @var{d}, @var{e})
Create a pentadiagonal Toeplitz matrix (sparse).

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("tridiag", @var{x}, @var{y}, @var{z})
@deftypefnx {Function File} {@var{a} =} gallery ("tridiag", @var{n})
@deftypefnx {Function File} {@var{a} =} gallery ("tridiag", @var{n}, @var{c}, @var{d}, @var{e})
Create a tridiagonal matrix (sparse).

@end deftypefn

@deftypefn  {Function File} {@var{t} =} gallery ("triw", @var{n})
@deftypefnx {Function File} {@var{t} =} gallery ("triw", @var{n}, @var{alpha})
@deftypefnx {Function File} {@var{t} =} gallery ("triw", @var{n}, @var{alpha}, @var{k})
Create an upper triangular matrix discussed by
@nospell{Kahan, Golub, and Wilkinson}.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("uniformdata", [@var{M} @var{N} @dots{}], @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("uniformdata", @var{M}, @var{N}, @dots{}, @var{j})
@deftypefnx {Function File} {@var{a} =} gallery ("uniformdata", @dots{}, "@var{class}")
Create a matrix with random samples from the standard uniform distribution
(range [0,1]).

The first input is a matrix of dimensions describing the size of the output.
The dimensions can also be input as comma-separated arguments.

The input @var{j} is an integer index in the range [0, 2^32-1].  The
values of the output matrix are always exactly the same
(reproducibility) for a given size input and @var{j} index.

The final optional argument determines the class of the resulting matrix.
Possible values for @var{class}: @qcode{"single"}, @qcode{"double"}.
The default is @qcode{"double"}.

@end deftypefn

@deftypefn  {Function File} {@var{a} =} gallery ("wathen", @var{nx}, @var{ny})
@deftypefnx {Function File} {@var{a} =} gallery ("wathen", @var{nx}, @var{ny}, @var{k})
Create the @nospell{Wathen} matrix.

@end deftypefn

@deftypefn {Function File} {[@var{a}, @var{b}] =} gallery ("wilk", @var{n})
Create various specific matrices devised/discussed by Wilkinson.

@end deftypefn


@c hadamard scripts/special-matrix/hadamard.m
@anchor{XREFhadamard}
@deftypefn {Function File} {} hadamard (@var{n})
Construct a Hadamard matrix (@nospell{Hn}) of size @var{n}-by-@var{n}.  The
size @var{n} must be of the form @math{2^k * p} in which
p is one of 1, 12, 20 or 28.  The returned matrix is normalized,
meaning @w{@code{Hn(:,1) == 1}} and @w{@code{Hn(1,:) == 1}}.

Some of the properties of Hadamard matrices are:

@itemize @bullet
@item
@code{kron (Hm, Hn)} is a Hadamard matrix of size @var{m}-by-@var{n}.

@item
@code{Hn * Hn' = @var{n} * eye (@var{n})}.

@item
The rows of @nospell{Hn} are orthogonal.

@item
@code{det (@var{A}) <= abs (det (Hn))} for all @var{A} with
@w{@code{abs (@var{A}(i, j)) <= 1}}.

@item
Multiplying any row or column by -1 and the matrix will remain a Hadamard
matrix.
@end itemize
@seealso{@ref{XREFcompan,,compan}, @ref{XREFhankel,,hankel}, @ref{XREFtoeplitz,,toeplitz}}
@end deftypefn


@c hankel scripts/special-matrix/hankel.m
@anchor{XREFhankel}
@deftypefn  {Function File} {} hankel (@var{c})
@deftypefnx {Function File} {} hankel (@var{c}, @var{r})
Return the Hankel matrix constructed from the first column @var{c}, and
(optionally) the last row @var{r}.  If the last element of @var{c} is
not the same as the first element of @var{r}, the last element of
@var{c} is used.  If the second argument is omitted, it is assumed to
be a vector of zeros with the same size as @var{c}.

A Hankel matrix formed from an m-vector @var{c}, and an n-vector
@var{r}, has the elements
@tex
$$
H(i, j) = \cases{c_{i+j-1},&$i+j-1\le m$;\cr r_{i+j-m},&otherwise.\cr}
$$
@end tex
@ifnottex

@example
@group
H(i,j) = c(i+j-1),  i+j-1 <= m;
H(i,j) = r(i+j-m),  otherwise
@end group
@end example

@end ifnottex
@seealso{@ref{XREFhadamard,,hadamard}, @ref{XREFtoeplitz,,toeplitz}}
@end deftypefn


@c hilb scripts/special-matrix/hilb.m
@anchor{XREFhilb}
@deftypefn {Function File} {} hilb (@var{n})
Return the Hilbert matrix of order @var{n}.  The @math{i,j} element
of a Hilbert matrix is defined as
@tex
$$
H(i, j) = {1 \over (i + j - 1)}
$$
@end tex
@ifnottex

@example
H(i, j) = 1 / (i + j - 1)
@end example

@end ifnottex

Hilbert matrices are close to being singular which make them difficult to
invert with numerical routines.
Comparing the condition number of a random matrix 5x5 matrix with that of
a Hilbert matrix of order 5 reveals just how difficult the problem is.

@example
@group
cond (rand (5))
   @result{} 14.392
cond (hilb (5))
   @result{} 4.7661e+05
@end group
@end example

@seealso{@ref{XREFinvhilb,,invhilb}}
@end deftypefn


@c invhilb scripts/special-matrix/invhilb.m
@anchor{XREFinvhilb}
@deftypefn {Function File} {} invhilb (@var{n})
Return the inverse of the Hilbert matrix of order @var{n}.  This can be
computed exactly using
@tex
$$\eqalign{
  A_{ij} &= -1^{i+j} (i+j-1)
             \left( \matrix{n+i-1 \cr n-j } \right)
             \left( \matrix{n+j-1 \cr n-i } \right)
             \left( \matrix{i+j-2 \cr i-2 } \right)^2 \cr
         &= { p(i)p(j) \over (i+j-1) }
}$$
where
$$
  p(k) = -1^k \left( \matrix{ k+n-1 \cr k-1 } \right)
              \left( \matrix{ n \cr k } \right)
$$
@end tex
@ifnottex

@example
@group

            (i+j)         /n+i-1\  /n+j-1\   /i+j-2\ 2
 A(i,j) = -1      (i+j-1)(       )(       ) (       )
                          \ n-j /  \ n-i /   \ i-2 /

        = p(i) p(j) / (i+j-1)

@end group
@end example

@noindent
where

@example
@group
             k  /k+n-1\   /n\
    p(k) = -1  (       ) (   )
                \ k-1 /   \k/
@end group
@end example

@end ifnottex
The validity of this formula can easily be checked by expanding
the binomial coefficients in both formulas as factorials.  It can
be derived more directly via the theory of Cauchy matrices.
See @nospell{J. W. Demmel}, @cite{Applied Numerical Linear Algebra}, p. 92.

Compare this with the numerical calculation of @code{inverse (hilb (n))},
which suffers from the ill-conditioning of the Hilbert matrix, and the
finite precision of your computer's floating point arithmetic.
@seealso{@ref{XREFhilb,,hilb}}
@end deftypefn


@c magic scripts/special-matrix/magic.m
@anchor{XREFmagic}
@deftypefn {Function File} {} magic (@var{n})

Create an @var{n}-by-@var{n} magic square.  A magic square is an arrangement
of the integers @code{1:n^2} such that the row sums, column sums, and
diagonal sums are all equal to the same value.

Note: @var{n} must be greater than 2 for the magic square to exist.
@end deftypefn


@c pascal scripts/special-matrix/pascal.m
@anchor{XREFpascal}
@deftypefn  {Function File} {} pascal (@var{n})
@deftypefnx {Function File} {} pascal (@var{n}, @var{t})
Return the Pascal matrix of order @var{n} if @code{@var{t} = 0}.  @var{t}
defaults to 0.  Return the pseudo-lower triangular Cholesky@tie{}factor of
the Pascal matrix if @code{@var{t} = 1} (The sign of some columns may be
negative).  This matrix is its own inverse, that is @code{pascal (@var{n},
1) ^ 2 == eye (@var{n})}.  If @code{@var{t} = -1}, return the true
Cholesky@tie{}factor with strictly positive values on the diagonal.  If
@code{@var{t} = 2}, return a transposed and permuted version of @code{pascal
(@var{n}, 1)}, which is the cube root of the identity matrix.  That is,
@code{pascal (@var{n}, 2) ^ 3 == eye (@var{n})}.

@seealso{@ref{XREFchol,,chol}}
@end deftypefn


@c rosser scripts/special-matrix/rosser.m
@anchor{XREFrosser}
@deftypefn {Function File} {} rosser ()
Return the Rosser matrix.  This is a difficult test case used to evaluate
eigenvalue algorithms.

@seealso{@ref{XREFwilkinson,,wilkinson}, @ref{XREFeig,,eig}}
@end deftypefn


@c toeplitz scripts/special-matrix/toeplitz.m
@anchor{XREFtoeplitz}
@deftypefn  {Function File} {} toeplitz (@var{c})
@deftypefnx {Function File} {} toeplitz (@var{c}, @var{r})
Return the Toeplitz matrix constructed from the first column @var{c},
and (optionally) the first row @var{r}.  If the first element of @var{r}
is not the same as the first element of @var{c}, the first element of
@var{c} is used.  If the second argument is omitted, the first row is
taken to be the same as the first column.

A square Toeplitz matrix has the form:
@tex
$$
\left[\matrix{c_0    & r_1     & r_2      & \cdots & r_n\cr
              c_1    & c_0     & r_1      & \cdots & r_{n-1}\cr
              c_2    & c_1     & c_0      & \cdots & r_{n-2}\cr
              \vdots & \vdots  & \vdots   & \ddots & \vdots\cr
              c_n    & c_{n-1} & c_{n-2} & \ldots & c_0}\right]
$$
@end tex
@ifnottex

@example
@group
c(0)  r(1)   r(2)  @dots{}  r(n)
c(1)  c(0)   r(1)  @dots{} r(n-1)
c(2)  c(1)   c(0)  @dots{} r(n-2)
 .     .      .   .      .
 .     .      .     .    .
 .     .      .       .  .
c(n) c(n-1) c(n-2) @dots{}  c(0)
@end group
@end example

@end ifnottex
@seealso{@ref{XREFhankel,,hankel}}
@end deftypefn


@c vander scripts/special-matrix/vander.m
@anchor{XREFvander}
@deftypefn  {Function File} {} vander (@var{c})
@deftypefnx {Function File} {} vander (@var{c}, @var{n})
Return the Vandermonde matrix whose next to last column is @var{c}.
If @var{n} is specified, it determines the number of columns;
otherwise, @var{n} is taken to be equal to the length of @var{c}.

A Vandermonde matrix has the form:
@tex
$$
\left[\matrix{c_1^{n-1}  & \cdots & c_1^2  & c_1    & 1      \cr
              c_2^{n-1}  & \cdots & c_2^2  & c_2    & 1      \cr
              \vdots     & \ddots & \vdots & \vdots & \vdots \cr
              c_n^{n-1}  & \cdots & c_n^2  & c_n    & 1      }\right]
$$
@end tex
@ifnottex

@example
@group
c(1)^(n-1) @dots{} c(1)^2  c(1)  1
c(2)^(n-1) @dots{} c(2)^2  c(2)  1
    .     .      .      .    .
    .       .    .      .    .
    .         .  .      .    .
c(n)^(n-1) @dots{} c(n)^2  c(n)  1
@end group
@end example

@end ifnottex
@seealso{@ref{XREFpolyfit,,polyfit}}
@end deftypefn


@c wilkinson scripts/special-matrix/wilkinson.m
@anchor{XREFwilkinson}
@deftypefn {Function File} {} wilkinson (@var{n})
Return the Wilkinson matrix of order @var{n}.  Wilkinson matrices are
symmetric and tridiagonal with pairs of nearly, but not exactly, equal
eigenvalues.  They are useful in testing the behavior and performance
of eigenvalue solvers.

@seealso{@ref{XREFrosser,,rosser}, @ref{XREFeig,,eig}}
@end deftypefn

