Arithmetic
**********

Unless otherwise noted, all of the functions described in this chapter will work for real and complex scalar or matrix arguments.

Utility Functions
=================

The following functions are available for working with complex numbers. Each expects a single argument.  They are called mapping functions because when given a matrix argument, they apply the given function to each element of the matrix.

 -- Mapping Function: ceil (X)
     Return the smallest integer not less than X.  If X is complex, return ceil (real (X)) + ceil (imag (X)) * I.

 -- Mapping Function: exp (X)
     Compute the exponential of X.  To compute the matrix exponential, see Linear Algebra.

 -- Mapping Function: fix (X)
     Truncate X toward zero.  If X is complex, return fix (real (X)) + fix (imag (X)) * I.

 -- Mapping Function: floor (X)
     Return the largest integer not greater than X.  If X is complex, return floor (real (X)) + floor (imag (X)) * I.

 -- Loadable Function: G = gcd (A1, ...)
 -- Loadable Function: [G, V1, ...] = gcd (A1, ...)

     If a single argument is given then compute the greatest common divisor of the elements of this argument. Otherwise if more than one argument is given all arguments must be the same size or scalar. In this case the greatest common divisor is calculated for element individually. All elements must be integers. For example,

          gcd ([15, 20])
              =>  5

     and

          gcd ([15, 9], [20 18])
              =>  5  9

     Optional return arguments V1, etc, contain integer vectors such that,

          G = V1 .* A1 + V2 .* A2 + ...

     For backward compatiability with previous versions of this function, when all arguments are scalr, a single return argument V1 containing all of the values of V1, ... is acceptable.

lcm, min, max, ceil, and floor

 -- Mapping Function: lcm (X, ...)
     Compute the least common multiple of the elements elements of X, or the list of all the arguments.  For example,

          lcm (a1, ..., ak)

     is the same as

          lcm ([a1, ..., ak]).

     All elements must be the same size or scalar.

gcd, min, max, ceil, and floor

 -- Mapping Function: log (X)
     Compute the natural logarithm for each element of X.  To compute the matrix logarithm, see Linear Algebra.

log2, log10, logspace, and exp

 -- Mapping Function: log10 (X)
     Compute the base-10 logarithm for each element of X.

log, log2, logspace, and exp

 -- Mapping Function: log2 (X)
 -- Mapping Function: [F, E] = log2 (X)
     Compute the base-2 logarithm of X.  With two outputs, returns F and E such that 1/2 <= abs(f) < 1 and x = f * 2^e.

log, log10, logspace, and exp

 -- Mapping Function: max (X, Y, DIM)
 -- Mapping Function: [W, IW] = max (X)
     For a vector argument, return the maximum value.  For a matrix argument, return the maximum value from each column, as a row vector, or over the dimension DIM if defined. For two matrices (or a matrix and scalar), return the pair-wise maximum. Thus,

          max (max (X))

     returns the largest element of X, and

          max (2:5, pi)
              =>  3.1416  3.1416  4.0000  5.0000

     compares each element of the range 2:5 with pi, and returns a row vector of the maximum values.

     For complex arguments, the magnitude of the elements are used for comparison.

     If called with one input and two output arguments, max also returns the first index of the maximum value(s). Thus,

          [x, ix] = max ([1, 3, 5, 2, 5])
              =>  x = 5
                  ix = 3

 -- Mapping Function: min (X, Y, DIM)
 -- Mapping Function: [W, IW] = min (X)
     For a vector argument, return the minimum value.  For a matrix argument, return the minimum value from each column, as a row vector, or over the dimension DIM if defined. For two matrices (or a matrix and scalar), return the pair-wise minimum. Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
              =>  2.0000  3.0000  3.1416  3.1416

     compares each element of the range 2:5 with pi, and returns a row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for comparison.

     If called with one input and two output arguments, min also returns the first index of the minimum value(s). Thus,

          [x, ix] = min ([1, 3, 0, 2, 5])
              =>  x = 0
                  ix = 3

 -- Mapping Function: mod (X, Y)
     Compute modulo function, using

          x - y .* floor (x ./ y)

     Note that this handles negative numbers correctly: mod (-1, 3) is 2, not -1 as rem (-1, 3) returns. Also, mod (X, 0) returns X.

     An error message is printed if the dimensions of the arguments do not agree, or if either of the arguments is complex.

rem, round

 -- Function File: nextpow2 (X)
     If X is a scalar, returns the first integer N such that 2^n >= abs (x).

     If X is a vector, return nextpow2 (length (X)).

pow2

 -- Mapping Function: pow2 (X)
 -- Mapping Function: pow2 (F, E)
     With one argument, computes 2 .^ x for each element of X.  With two arguments, returns f .* (2 .^ e).

nextpow2

 -- Mapping Function: rem (X, Y)
     Return the remainder of X / Y, computed using the expression

          x - y .* fix (x ./ y)

     An error message is printed if the dimensions of the arguments do not agree, or if either of the arguments is complex.

mod, round

 -- Mapping Function: round (X)
     Return the integer nearest to X.  If X is complex, return round (real (X)) + round (imag (X)) * I.

rem

 -- Mapping Function: sign (X)
     Compute the signum function, which is defined as

                     -1, x < 0;
          sign (x) =  0, x = 0;
                      1, x > 0.

     For complex arguments, sign returns x ./ abs (X).

 -- Mapping Function: sqrt (X)
     Compute the square root of X.  If X is negative, a complex result is returned.  To compute the matrix square root, see Linear Algebra.

Complex Arithmetic
==================

The following functions are available for working with complex numbers.  Each expects a single argument.  Given a matrix they work on an element by element basis.  In the descriptions of the following functions, Z is the complex number X + IY, where I is defined as sqrt (-1).

 -- Mapping Function: abs (Z)
     Compute the magnitude of Z, defined as |Z| = sqrt (x^2 + y^2).

     For example,

          abs (3 + 4i)
               => 5

 -- Mapping Function: arg (Z)
 -- Mapping Function: angle (Z)
     Compute the argument of Z, defined as THETA = atan (Y/X).

     in radians.

     For example,

          arg (3 + 4i)
               => 0.92730

 -- Mapping Function: conj (Z)
     Return the complex conjugate of Z, defined as conj (Z) = X - IY.

real and imag

 -- Mapping Function: imag (Z)
     Return the imaginary part of Z as a real number.

real and conj

 -- Mapping Function: real (Z)
     Return the real part of Z.

imag and conj

Trigonometry
============

Octave provides the following trigonometric functions.  Angles are specified in radians.  To convert from degrees to radians multipy by pi/180 (e.g. sin (30 * pi/180) returns the sine of 30 degrees).

 -- Mapping Function: sin (X)
     Compute the sine of each element of X.

 -- Mapping Function: cos (X)
     Compute the cosine of each element of X.

 -- Mapping Function: tan (Z)
     Compute tangent of each element of X.

 -- Mapping Function: sec (X)
     Compute the secant of each element of X.

 -- Mapping Function: csc (X)
     Compute the cosecant of each element of X.

 -- Mapping Function: cot (X)
     Compute the cotangent of each element of X.

 -- Mapping Function: asin (X)
     Compute the inverse sine of each element of X.

 -- Mapping Function: acos (X)
     Compute the inverse cosine of each element of X.

 -- Mapping Function: atan (X)
     Compute the inverse tangent of each element of X.

 -- Mapping Function: asec (X)
     Compute the inverse secant of each element of X.

 -- Mapping Function: acsc (X)
     Compute the inverse cosecant of each element of X.

 -- Mapping Function: acot (X)
     Compute the inverse cotangent of each element of X.

 -- Mapping Function: sinh (X)
     Compute the inverse hyperbolic sine of each element of X.

 -- Mapping Function: cosh (X)
     Compute the hyperbolic cosine of each element of X.

 -- Mapping Function: tanh (X)
     Compute hyperbolic tangent of each element of X.

 -- Mapping Function: sech (X)
     Compute the hyperbolic secant of each element of X.

 -- Mapping Function: csch (X)
     Compute the hyperbolic cosecant of each element of X.

 -- Mapping Function: coth (X)
     Compute the hyperbolic cotangent of each element of X.

 -- Mapping Function: asinh (X)
     Compute the inverse hyperbolic sine of each element of X.

 -- Mapping Function: acosh (X)
     Compute the inverse hyperbolic cosine of each element of X.

 -- Mapping Function: atanh (X)
     Compute the inverse hyperbolic tangent of each element of X.

 -- Mapping Function: asech (X)
     Compute the inverse hyperbolic secant of each element of X.

 -- Mapping Function: acsch (X)
     Compute the inverse hyperbolic cosecant of each element of X.

 -- Mapping Function: acoth (X)
     Compute the inverse hyperbolic cotangent of each element of X.

Each of these functions expect a single argument.  For matrix arguments, they work on an element by element basis.  For example,

     sin ([1, 2; 3, 4])
          =>  0.84147   0.90930
              0.14112  -0.75680

 -- Mapping Function: atan2 (Y, X)
     Compute atan (Y / X) for corresponding elements of Y and X.  The result is in range -pi to pi.

Sums and Products
=================

 -- Built-in Function: sum (X, DIM)
     Sum of elements along dimension DIM.  If DIM is omitted, it defaults to 1 (column-wise sum).

     As a special case, if X is a vector and DIM is omitted, return the sum of the elements.

 -- Built-in Function: prod (X, DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it defaults to 1 (column-wise products).

     As a special case, if X is a vector and DIM is omitted, return the product of the elements.

 -- Built-in Function: cumsum (X, DIM)
     Cumulative sum of elements along dimension DIM.  If DIM is omitted, it defaults to 1 (column-wise cumulative sums).

     As a special case, if X is a vector and DIM is omitted, return the cumulative sum of the elements as a vector with the same orientation as X.

 -- Built-in Function: cumprod (X, DIM)
     Cumulative product of elements along dimension DIM.  If DIM is omitted, it defaults to 1 (column-wise cumulative products).

     As a special case, if X is a vector and DIM is omitted, return the cumulative product of the elements as a vector with the same orientation as X.

 -- Built-in Function: sumsq (X, DIM)
     Sum of squares of elements along dimension DIM.  If DIM is omitted, it defaults to 1 (column-wise sum of squares).

     As a special case, if X is a vector and DIM is omitted, return the sum of squares of the elements.

     This function is conceptually equivalent to computing

          sum (x .* conj (x), dim)

     but it uses less memory and avoids calling conj if X is real.

Special Functions
=================

 -- Loadable Function: [J, IERR] = besselj (ALPHA, X, OPT)
 -- Loadable Function: [Y, IERR] = bessely (ALPHA, X, OPT)
 -- Loadable Function: [I, IERR] = besseli (ALPHA, X, OPT)
 -- Loadable Function: [K, IERR] = besselk (ALPHA, X, OPT)
 -- Loadable Function: [H, IERR] = besselh (ALPHA, K, X, OPT)
     Compute Bessel or Hankel functions of various kinds:

     besselj
          Bessel functions of the first kind.

     bessely
          Bessel functions of the second kind.

     besseli
          Modified Bessel functions of the first kind.

     besselk
          Modified Bessel functions of the second kind.

     besselh
          Compute Hankel functions of the first (K = 1) or second (K = 2) kind.

     If the argument OPT is supplied, the result is scaled by the exp (-I*X) for K = 1 or exp (I*X) for K = 2.

     If ALPHA is a scalar, the result is the same size as X. If X is a scalar, the result is the same size as ALPHA. If ALPHA is a row vector and X is a column vector, the result is a matrix with length (X) rows and length (ALPHA) columns.  Otherwise, ALPHA and X must conform and the result will be the same size.

     The value of ALPHA must be real.  The value of X may be complex.

     If requested, IERR contains the following status information and is the same size as the result.

      0. Normal return.

      1. Input error, return NaN.

      2. Overflow, return Inf.

      3. Loss of significance by argument reduction results in less than half of machine accuracy.

      4. Complete loss of significance by argument reduction, return NaN.

      5. Error---no computation, algorithm termination condition not met, return NaN.

 -- Loadable Function: [A, IERR] = airy (K, Z, OPT)
     Compute Airy functions of the first and second kind, and their derivatives.

            K   Function   Scale factor (if a third argument is supplied)
           ---  --------   ----------------------------------------------
            0   Ai (Z)     exp ((2/3) * Z * sqrt (Z))
            1   dAi(Z)/dZ  exp ((2/3) * Z * sqrt (Z))
            2   Bi (Z)     exp (-abs (real ((2/3) * Z *sqrt (Z))))
            3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z *sqrt (Z))))

     The function call airy (Z) is equivalent to airy (0, Z).

     The result is the same size as Z.

     If requested, IERR contains the following status information and is the same size as the result.

      0. Normal return.

      1. Input error, return NaN.

      2. Overflow, return Inf.

      3. Loss of significance by argument reduction results in less than half of machine accuracy.

      4. Complete loss of significance by argument reduction, return NaN.

      5. Error---no computation, algorithm termination condition not met, return NaN

 -- Mapping Function: beta (A, B)
     Return the Beta function,

          beta (a, b) = gamma (a) * gamma (b) / gamma (a + b).

 -- Mapping Function: betainc (X, A, B)
     Return the incomplete Beta function,

                                                x
                                               /
          betainc (x, a, b) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt.
                                               /
                                            t=0

     If x has more than one component, both A and B must be scalars.  If X is a scalar, A and B must be of compatible dimensions.

 -- Mapping Function: bincoeff (N, K)
     Return the binomial coefficient of N and K, defined as

           /   \
           | n |    n (n-1) (n-2) ... (n-k+1)
           |   |  = -------------------------
           | k |               k!
           \   /

     For example,

          bincoeff (5, 2)
          => 10

 -- Mapping Function: erf (Z)
     Computes the error function,

                                   z
                                  /
          erf (z) = (2/sqrt (pi)) | e^(-t^2) dt
                                  /
                               t=0

erfc and erfinv

 -- Mapping Function: erfc (Z)
     Computes the complementary error function, 1 - erf (Z).

erf and erfinv

 -- Mapping Function: erfinv (Z)
     Computes the inverse of the error function.

erf and erfc

 -- Mapping Function: gamma (Z)
     Computes the Gamma function,

                      infinity
                      /
          gamma (z) = | t^(z-1) exp (-t) dt.
                      /
                   t=0

gammai and lgamma

 -- Mapping Function: gammainc (X, A)
     Computes the incomplete gamma function,

                                          x
                                1        /
          gammainc (x, a) = ---------    | exp (-t) t^(a-1) dt
                            gamma (a)    /
                                      t=0

     If A is scalar, then gammainc (X, A) is returned for each element of X and vice versa.

     If neither X nor A is scalar, the sizes of X and A must agree, and GAMMAINC is applied element-by-element.

gamma and lgamma

 -- Mapping Function: lgamma (A, X)
 -- Mapping Function: gammaln (A, X)
     Return the natural logarithm of the gamma function.

gamma and gammai

 -- Function File: cross (X, Y, DIM)
     Computes the vector cross product of the two 3-dimensional vectors X and Y.

          cross ([1,1,0], [0,1,1])
          => [ 1; -1; 1 ]

     If X and Y are matrices, the cross product is applied along the first dimension with 3 elements. The optional argument DIM is used to force the cross product to be calculated along the dimension defiend by DIM.

 -- Function File: commutation_matrix (M, N)
     Return the commutation matrix K(m,n) which is the unique M*N by M*N matrix such that K(m,n) * vec(A) = vec(A') for all m by n matrices A.

     If only one argument M is given, K(m,m) is returned.

     See Magnus and Neudecker (1988), Matrix differential calculus with applications in statistics and econometrics.

 -- Function File: duplication_matrix (N)
     Return the duplication matrix Dn which is the unique n^2 by n*(n+1)/2 matrix such that Dn vech (A) = vec (A) for all symmetric n by n matrices A.

     See Magnus and Neudecker (1988), Matrix differential calculus with applications in statistics and econometrics.

Coordinate Transformations
==========================

 -- Function File: [THETA, R] = cart2pol (X, Y)
 -- Function File: [THETA, R, Z] = cart2pol (X, Y, Z)
     Transform cartesian to polar or cylindrical coordinates. X, Y (and Z) must be of same shape. THETA describes the angle relative to the x - axis. R is the distance to the z - axis (0, 0, z).

pol2cart, cart2sph, sph2cart

 -- Function File: [X, Y] = pol2cart (THETA, R)
 -- Function File: [X, Y, Z] = pol2cart (THETA, R, Z)
     Transform polar or cylindrical to cartesian coordinates. THETA, R (and Z) must be of same shape. THETA describes the angle relative to the x - axis. R is the distance to the z - axis (0, 0, z).

cart2pol, cart2sph, sph2cart

 -- Function File: [THETA, PHI, R] = cart2sph (X, Y, Z)
     Transform cartesian to spherical coordinates. X, Y and Z must be of same shape. THETA describes the angle relative to the x - axis. PHI is the angle relative to the xy - plane. R is the distance to the origin (0, 0, 0).

pol2cart, cart2pol, sph2cart

 -- Function File: [X, Y, Z] = sph2cart (THETA, PHI, R)
     Transform spherical to cartesian coordinates. X, Y and Z must be of same shape. THETA describes the angle relative to the x-axis. PHI is the angle relative to the xy-plane. R is the distance to the origin (0, 0, 0).

pol2cart, cart2pol, cart2sph

Mathematical Constants
======================

 -- Built-in Variable: I
 -- Built-in Variable: J
 -- Built-in Variable: i
 -- Built-in Variable: j
     A pure imaginary number, defined as sqrt (-1). These built-in variables behave like functions so you can use the names for other purposes.  If you use them as variables and assign values to them and then clear them, they once again assume their special predefined values see Status of Variables.

 -- Built-in Variable: Inf
 -- Built-in Variable: inf
     Infinity.  This is the result of an operation like 1/0, or an operation that results in a floating point overflow.

 -- Built-in Variable: NaN
 -- Built-in Variable: nan
     Not a number.  This is the result of an operation like 0/0, or Inf - Inf, or any operation with a NaN.

     Note that NaN always compares not equal to NaN.  This behavior is specified by the IEEE standard for floating point arithmetic.  To find NaN values, you must use the isnan function.

 -- Built-in Variable: pi
     The ratio of the circumference of a circle to its diameter. Internally, pi is computed as 4.0 * atan (1.0).

 -- Built-in Variable: e
     The base of natural logarithms.  The constant E satisfies the equation log (E) = 1.

 -- Built-in Variable: eps
     The machine precision.  More precisely, eps is the largest relative spacing between any two adjacent numbers in the machine's floating point system.  This number is obviously system-dependent.  On machines that support 64 bit IEEE floating point arithmetic, eps is approximately 2.2204e-16.

 -- Built-in Variable: realmax
     The largest floating point number that is representable.  The actual value is system-dependent.  On machines that support 64-bit IEEE floating point arithmetic, realmax is approximately 1.7977e+308

 -- Built-in Variable: realmin
     The smallest normalized floating point number that is representable. The actual value is system-dependent.  On machines that support 64-bit IEEE floating point arithmetic, realmin is approximately 2.2251e-308