This is octave.info, produced by makeinfo version 6.7 from octave.texi.

INFO-DIR-SECTION Math
START-INFO-DIR-ENTRY
* Octave: (octave).             Interactive language for numerical computations.
END-INFO-DIR-ENTRY

Copyright © 1996-2020 John W. Eaton.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions.


File: octave.info,  Node: Basic Statistical Functions,  Next: Correlation and Regression Analysis,  Prev: Statistics on Sliding Windows of Data,  Up: Statistics

26.3 Basic Statistical Functions
================================

Octave supports various helpful statistical functions.  Many are useful
as initial steps to prepare a data set for further analysis.  Others
provide different measures from those of the basic descriptive
statistics.

 -- : center (X)
 -- : center (X, DIM)
     Center data by subtracting its mean.

     If X is a vector, subtract its mean.

     If X is a matrix, do the above for each column.

     If the optional argument DIM is given, operate along this
     dimension.

     Programming Note: ‘center’ has obvious application for normalizing
     statistical data.  It is also useful for improving the precision of
     general numerical calculations.  Whenever there is a large value
     that is common to a batch of data, the mean can be subtracted off,
     the calculation performed, and then the mean added back to obtain
     the final answer.

     See also: *note zscore: XREFzscore.

 -- : Z = zscore (X)
 -- : Z = zscore (X, OPT)
 -- : Z = zscore (X, OPT, DIM)
 -- : [Z, MU, SIGMA] = zscore (...)
     Compute the Z score of X.

     If X is a vector, subtract its mean and divide by its standard
     deviation.  If the standard deviation is zero, divide by 1 instead.

     The optional parameter OPT determines the normalization to use when
     computing the standard deviation and has the same definition as the
     corresponding parameter for ‘std’.

     If X is a matrix, calculate along the first non-singleton
     dimension.  If the third optional argument DIM is given, operate
     along this dimension.

     The optional outputs MU and SIGMA contain the mean and standard
     deviation.

     See also: *note mean: XREFmean, *note std: XREFstd, *note center:
     XREFcenter.

 -- : N = histc (X, EDGES)
 -- : N = histc (X, EDGES, DIM)
 -- : [N, IDX] = histc (...)
     Compute histogram counts.

     When X is a vector, the function counts the number of elements of X
     that fall in the histogram bins defined by EDGES.  This must be a
     vector of monotonically increasing values that define the edges of
     the histogram bins.  ‘N(k)’ contains the number of elements in X
     for which ‘EDGES(k) <= X < EDGES(k+1)’.  The final element of N
     contains the number of elements of X exactly equal to the last
     element of EDGES.

     When X is an N-dimensional array, the computation is carried out
     along dimension DIM.  If not specified DIM defaults to the first
     non-singleton dimension.

     When a second output argument is requested an index matrix is also
     returned.  The IDX matrix has the same size as X.  Each element of
     IDX contains the index of the histogram bin in which the
     corresponding element of X was counted.

     See also: *note hist: XREFhist.

‘unique’ function documented at *note unique: XREFunique. is often
useful for statistics.

 -- : C = nchoosek (N, K)
 -- : C = nchoosek (SET, K)

     Compute the binomial coefficient of N or list all possible
     combinations of a SET of items.

     If N is a scalar then calculate the binomial coefficient of N and K
     which is defined as

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

     This is the number of combinations of N items taken in groups of
     size K.

     If the first argument is a vector, SET, then generate all
     combinations of the elements of SET, taken K at a time, with one
     row per combination.  The result C has K columns and
     ‘nchoosek (length (SET), K)’ rows.

     For example:

     How many ways can three items be grouped into pairs?

          nchoosek (3, 2)
             ⇒ 3

     What are the possible pairs?

          nchoosek (1:3, 2)
             ⇒  1   2
                 1   3
                 2   3

     Programming Note: When calculating the binomial coefficient
     ‘nchoosek’ works only for non-negative, integer arguments.  Use
     ‘bincoeff’ for non-integer and negative scalar arguments, or for
     computing many binomial coefficients at once with vector inputs for
     N or K.

     See also: *note bincoeff: XREFbincoeff, *note perms: XREFperms.

 -- : perms (V)
     Generate all permutations of vector V with one row per permutation.

     Results are returned in inverse lexicographic order.  The result
     has size ‘factorial (N) * N’, where N is the length of V.  Any
     repetitions are included in the output.  To generate just the
     unique permutations use ‘unique (perms (V), "rows")(end:-1:1,:)’.

     Example

          perms ([1, 2, 3])
          ⇒
            3   2   1
            3   1   2
            2   3   1
            2   1   3
            1   3   2
            1   2   3

     Programming Note: The maximum length of V should be less than or
     equal to 10 to limit memory consumption.

     See also: *note permute: XREFpermute, *note randperm: XREFrandperm,
     *note nchoosek: XREFnchoosek.

 -- : ranks (X)
 -- : ranks (X, DIM)
 -- : ranks (X, DIM, RTYPE)
     Return the ranks (in the sense of order statistics) of X along the
     first non-singleton dimension adjusted for ties.

     If the optional DIM argument is given, operate along this
     dimension.

     The optional parameter RTYPE determines how ties are handled.  All
     examples below assume an input of ‘[ 1, 2, 2, 4 ]’.

     0 or "fractional" (default) for fractional ranking (1, 2.5,
          2.5, 4);

     1 or "competition" for competition ranking (1, 2, 2, 4);

     2 or "modified" for modified competition ranking (1, 3, 3, 4);

     3 or "ordinal" for ordinal ranking (1, 2, 3, 4);

     4 or "dense" for dense ranking (1, 2, 2, 3).

     See also: *note spearman: XREFspearman, *note kendall: XREFkendall.

 -- : run_count (X, N)
 -- : run_count (X, N, DIM)
     Count the upward runs along the first non-singleton dimension of X
     of length 1, 2, ..., N-1 and greater than or equal to N.

     If the optional argument DIM is given then operate along this
     dimension.

     See also: *note runlength: XREFrunlength.

 -- : count = runlength (X)
 -- : [count, value] = runlength (X)
     Find the lengths of all sequences of common values.

     COUNT is a vector with the lengths of each repeated value.

     The optional output VALUE contains the value that was repeated in
     the sequence.

          runlength ([2, 2, 0, 4, 4, 4, 0, 1, 1, 1, 1])
          ⇒   2   1   3   1   4

     See also: *note run_count: XREFrun_count.


File: octave.info,  Node: Correlation and Regression Analysis,  Next: Distributions,  Prev: Basic Statistical Functions,  Up: Statistics

26.4 Correlation and Regression Analysis
========================================

 -- : cov (X)
 -- : cov (X, OPT)
 -- : cov (X, Y)
 -- : cov (X, Y, OPT)
     Compute the covariance matrix.

     If each row of X and Y is an observation, and each column is a
     variable, then the (I, J)-th entry of ‘cov (X, Y)’ is the
     covariance between the I-th variable in X and the J-th variable in
     Y.

          cov (X) = 1/(N-1) * SUM_i (X(i) - mean(X)) * (Y(i) - mean(Y))

     where N is the length of the X and Y vectors.

     If called with one argument, compute ‘cov (X, X)’, the covariance
     between the columns of X.

     The argument OPT determines the type of normalization to use.
     Valid values are

     0:
          normalize with N-1, provides the best unbiased estimator of
          the covariance [default]

     1:
          normalize with N, this provides the second moment around the
          mean

     Compatibility Note:: Octave always treats rows of X and Y as
     multivariate random variables.  For two inputs, however, MATLAB
     treats X and Y as two univariate distributions regardless of their
     shapes, and will calculate ‘cov ([X(:), Y(:)])’ whenever the number
     of elements in X and Y are equal.  This will result in a 2x2
     matrix.  Code relying on MATLAB’s definition will need to be
     changed when running in Octave.

     See also: *note corr: XREFcorr.

 -- : corr (X)
 -- : corr (X, Y)
     Compute matrix of correlation coefficients.

     If each row of X and Y is an observation and each column is a
     variable, then the (I, J)-th entry of ‘corr (X, Y)’ is the
     correlation between the I-th variable in X and the J-th variable in
     Y.

          corr (X,Y) = cov (X,Y) / (std (X) * std (Y))

     If called with one argument, compute ‘corr (X, X)’, the correlation
     between the columns of X.

     See also: *note cov: XREFcov.

 -- : R = corrcoef (X)
 -- : R = corrcoef (X, Y)
 -- : R = corrcoef (..., PARAM, VALUE, ...)
 -- : [R, P] = corrcoef (...)
 -- : [R, P, LCI, HCI] = corrcoef (...)
     Compute a matrix of correlation coefficients.

     X is an array where each column contains a variable and each row is
     an observation.

     If a second input Y (of the same size as X) is given then calculate
     the correlation coefficients between X and Y.

     PARAM, VALUE are optional pairs of parameters and values which
     modify the calculation.  Valid options are:

     "alpha"
          Confidence level used for the bounds of the confidence
          interval, LCI and HCI.  Default is 0.05, i.e., 95% confidence
          interval.

     "rows"
          Determine processing of NaN values.  Acceptable values are
          "all", "complete", and "pairwise".  Default is "all".  With
          "complete", only the rows without NaN values are considered.
          With "pairwise", the selection of NaN-free rows is made for
          each pair of variables.

     Output R is a matrix of Pearson’s product moment correlation
     coefficients for each pair of variables.

     Output P is a matrix of pair-wise p-values testing for the null
     hypothesis of a correlation coefficient of zero.

     Outputs LCI and HCI are matrices containing, respectively, the
     lower and higher bounds of the 95% confidence interval of each
     correlation coefficient.

     See also: *note corr: XREFcorr, *note cov: XREFcov.

 -- : spearman (X)
 -- : spearman (X, Y)
     Compute Spearman’s rank correlation coefficient RHO.

     For two data vectors X and Y, Spearman’s RHO is the correlation
     coefficient of the ranks of X and Y.

     If X and Y are drawn from independent distributions, RHO has zero
     mean and variance ‘1 / (N - 1)’, where N is the length of the X and
     Y vectors, and is asymptotically normally distributed.

     ‘spearman (X)’ is equivalent to ‘spearman (X, X)’.

     See also: *note ranks: XREFranks, *note kendall: XREFkendall.

 -- : kendall (X)
 -- : kendall (X, Y)
     Compute Kendall’s TAU.

     For two data vectors X, Y of common length N, Kendall’s TAU is the
     correlation of the signs of all rank differences of X and Y; i.e.,
     if both X and Y have distinct entries, then

                   1
          TAU = -------   SUM sign (Q(i) - Q(j)) * sign (R(i) - R(j))
                N (N-1)   i,j

     in which the Q(i) and R(i) are the ranks of X and Y, respectively.

     If X and Y are drawn from independent distributions, Kendall’s TAU
     is asymptotically normal with mean 0 and variance ‘(2 * (2N+5)) /
     (9 * N * (N-1))’.

     ‘kendall (X)’ is equivalent to ‘kendall (X, X)’.

     See also: *note ranks: XREFranks, *note spearman: XREFspearman.


File: octave.info,  Node: Distributions,  Next: Random Number Generation,  Prev: Correlation and Regression Analysis,  Up: Statistics

26.5 Distributions
==================

Octave has functions for computing the Probability Density Function
(PDF), the Cumulative Distribution function (CDF), and the quantile (the
inverse of the CDF) for arbitrary user-defined distributions (discrete)
and for experimental data (empirical).

   The following table summarizes the supported distributions (in
alphabetical order).

Distribution           PDF               CDF               Quantile
-----------------------------------------------------------------------------
Univariate Discrete    ‘discrete_pdf’    ‘discrete_cdf’    ‘discrete_inv’
Distribution
Empirical              ‘empirical_pdf’   ‘empirical_cdf’   ‘empirical_inv’
Distribution

 -- : discrete_pdf (X, V, P)
     For each element of X, compute the probability density function
     (PDF) at X of a univariate discrete distribution which assumes the
     values in V with probabilities P.

 -- : discrete_cdf (X, V, P)
     For each element of X, compute the cumulative distribution function
     (CDF) at X of a univariate discrete distribution which assumes the
     values in V with probabilities P.

 -- : discrete_inv (X, V, P)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the univariate distribution which assumes the values
     in V with probabilities P.

 -- : empirical_pdf (X, DATA)
     For each element of X, compute the probability density function
     (PDF) at X of the empirical distribution obtained from the
     univariate sample DATA.

 -- : empirical_cdf (X, DATA)
     For each element of X, compute the cumulative distribution function
     (CDF) at X of the empirical distribution obtained from the
     univariate sample DATA.

 -- : empirical_inv (X, DATA)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the empirical distribution obtained from the
     univariate sample DATA.


File: octave.info,  Node: Random Number Generation,  Prev: Distributions,  Up: Statistics

26.6 Random Number Generation
=============================

Octave can generate random numbers from a large number of distributions.
The random number generators are based on the random number generators
described in *note Special Utility Matrices::.

   The following table summarizes the available random number generators
(in alphabetical order).

Distribution                  Function
-----------------------------------------------------
Univariate Discrete           ‘discrete_rnd’
Distribution
Empirical Distribution        ‘empirical_rnd’
Exponential Distribution      ‘rande’
Gamma Distribution            ‘randg’
Poisson Distribution          ‘randp’
Standard Normal               ‘randn’
Distribution
Uniform Distribution          ‘rand’
Uniform Distribution          ‘randi’
(integers)

 -- : discrete_rnd (V, P)
 -- : discrete_rnd (V, P, R)
 -- : discrete_rnd (V, P, R, C, ...)
 -- : discrete_rnd (V, P, [SZ])
     Return a matrix of random samples from the univariate distribution
     which assumes the values in V with probabilities P.

     When called with a single size argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The size may also be specified with a vector of
     dimensions SZ.

     If no size arguments are given then the result matrix is the common
     size of V and P.

 -- : empirical_rnd (DATA)
 -- : empirical_rnd (DATA, R)
 -- : empirical_rnd (DATA, R, C, ...)
 -- : empirical_rnd (DATA, [SZ])
     Return a matrix of random samples from the empirical distribution
     obtained from the univariate sample DATA.

     When called with a single size argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The size may also be specified with a vector of
     dimensions SZ.

     If no size arguments are given then the result matrix is a random
     ordering of the sample DATA.


File: octave.info,  Node: Sets,  Next: Polynomial Manipulations,  Prev: Statistics,  Up: Top

27 Sets
*******

Octave has a number of functions for managing sets of data.  A set is
defined as a collection of unique elements and is typically represented
by a vector of numbers sorted in ascending order.  Any vector or matrix
can be converted to a set by removing duplicates through the use of the
‘unique’ function.  However, it isn’t necessary to explicitly create a
set as all of the functions which operate on sets will convert their
input to a set before proceeding.

 -- : unique (X)
 -- : unique (X, "rows")
 -- : unique (..., "sorted")
 -- : unique (..., "stable")
 -- : [Y, I, J] = unique (...)
 -- : [Y, I, J] = unique (..., "first")
 -- : [Y, I, J] = unique (..., "last")
 -- : [Y, I, J] = unique (..., "legacy")
     Return the unique elements of X.

     If the input X is a column vector then return a column vector;
     Otherwise, return a row vector.  X may also be a cell array of
     strings.

     If the optional argument "rows" is given then return the unique
     rows of X.  The input must be a 2-D numeric matrix to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input X.

     If requested, return column index vectors I and J such that ‘Y =
     X(I)’ and ‘X = Y(J)’.

     Additionally, if I is a requested output then one of the flags
     "first" or "last" may be given.  If "last" is specified, return the
     highest possible indices in I, otherwise, if "first" is specified,
     return the lowest.  The default is "first".

     Example 1 : sort order

          unique ([3, 1, 1, 2])
          ⇒ [1, 2, 3]
          unique ([3, 1, 1, 2], "stable")
          ⇒ [3, 1, 2]

     Example 2 : index selection

          [~, I] = unique ([3, 1, 1, 2], "first")
          ⇒ I = [2; 4; 1]
          [~, I] = unique ([3, 1, 1, 2], "last")
          ⇒ I = [3; 4; 1]

     Programming Notes: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.  Specifically,
     The index ordering flag is changed to "last", and the shape of the
     outputs I, J will follow the shape of the input X rather than
     always being column vectors.

     The third output, J, has not been implemented yet when the sort
     order is "stable".

     See also: *note union: XREFunion, *note intersect: XREFintersect,
     *note setdiff: XREFsetdiff, *note setxor: XREFsetxor, *note
     ismember: XREFismember.

* Menu:

* Set Operations::


File: octave.info,  Node: Set Operations,  Up: Sets

27.1 Set Operations
===================

Octave supports several basic set operations.  Octave can compute the
union, intersection, and difference of two sets.  Octave also supports
the _Exclusive Or_ set operation.

   The functions for set operations all work in the same way by
accepting two input sets and returning a third set.  As an example,
assume that ‘a’ and ‘b’ contains two sets, then

     union (a, b)

computes the union of the two sets.

   Finally, determining whether elements belong to a set can be done
with the ‘ismember’ function.  Because sets are ordered this operation
is very efficient and is of order O(log2(n)) which is preferable to the
‘find’ function which is of order O(n).

 -- : C = intersect (A, B)
 -- : C = intersect (A, B, "rows")
 -- : C = intersect (..., "sorted")
 -- : C = intersect (..., "stable")
 -- : C = intersect (..., "legacy")
 -- : [C, IA, IB] = intersect (...)

     Return the unique elements common to both A and B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return the common rows
     of A and B.  The inputs must be 2-D numeric matrices to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     If requested, return column index vectors IA and IB such that ‘C =
     A(IA)’ and ‘C = B(IB)’.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     setdiff: XREFsetdiff, *note setxor: XREFsetxor, *note ismember:
     XREFismember.

 -- : C = union (A, B)
 -- : C = union (A, B, "rows")
 -- : C = union (..., "sorted")
 -- : C = union (..., "stable")
 -- : C = union (..., "legacy")
 -- : [C, IA, IB] = union (...)

     Return the unique elements that are in either A or B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return rows that are in
     either A or B.  The inputs must be 2-D numeric matrices to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     The optional outputs IA and IB are column index vectors such that
     ‘A(IA)’ and ‘B(IB)’ are disjoint sets whose union is C.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note intersect: XREFintersect,
     *note setdiff: XREFsetdiff, *note setxor: XREFsetxor, *note
     ismember: XREFismember.

 -- : C = setdiff (A, B)
 -- : C = setdiff (A, B, "rows")
 -- : C = setdiff (..., "sorted")
 -- : C = setdiff (..., "stable")
 -- : C = setdiff (..., "legacy")
 -- : [C, IA] = setdiff (...)
     Return the unique elements in A that are not in B.

     If A is a row vector return a row vector; Otherwise, return a
     column vector.  The inputs may also be cell arrays of strings.

     If the optional input "rows" is given then return the rows in A
     that are not in B.  The inputs must be 2-D numeric matrices to use
     this option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     If requested, return the index vector IA such that ‘C = A(IA)’.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setxor: XREFsetxor, *note ismember:
     XREFismember.

 -- : C = setxor (A, B)
 -- : C = setxor (A, B, "rows")
 -- : C = setxor (..., "sorted")
 -- : C = setxor (..., "stable")
 -- : C = setxor (..., "legacy")
 -- : [C, IA, IB] = setxor (...)

     Return the unique elements exclusive to sets A or B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return the rows
     exclusive to sets A and B.  The inputs must be 2-D numeric matrices
     to use this option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     The optional outputs IA and IB are column index vectors such that
     ‘A(IA)’ and ‘B(IB)’ are disjoint sets whose union is C.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setdiff: XREFsetdiff, *note
     ismember: XREFismember.

 -- : TF = ismember (A, S)
 -- : TF = ismember (A, S, "rows")
 -- : [TF, S_IDX] = ismember (...)

     Return a logical matrix TF with the same shape as A which is true
     (1) if the element in A is found in S and false (0) if it is not.

     If a second output argument is requested then the index into S of
     each matching element is also returned.

          a = [3, 10, 1];
          s = [0:9];
          [tf, s_idx] = ismember (a, s)
               ⇒ tf = [1, 0, 1]
               ⇒ s_idx = [4, 0, 2]

     The inputs A and S may also be cell arrays.

          a = {"abc"};
          s = {"abc", "def"};
          [tf, s_idx] = ismember (a, s)
               ⇒ tf = 1
               ⇒ s_idx = 1

     If the optional third argument "rows" is given then compare rows in
     A with rows in S.  The inputs must be 2-D matrices with the same
     number of columns to use this option.

          a = [1:3; 5:7; 4:6];
          s = [0:2; 1:3; 2:4; 3:5; 4:6];
          [tf, s_idx] = ismember (a, s, "rows")
               ⇒ tf = logical ([1; 0; 1])
               ⇒ s_idx = [2; 0; 5];

     See also: *note lookup: XREFlookup, *note unique: XREFunique, *note
     union: XREFunion, *note intersect: XREFintersect, *note setdiff:
     XREFsetdiff, *note setxor: XREFsetxor.

 -- : powerset (A)
 -- : powerset (A, "rows")
     Compute the powerset (all subsets) of the set A.

     The set A must be a numerical matrix or a cell array of strings.
     The output will always be a cell array of either vectors or
     strings.

     With the optional argument "rows", each row of the set A is
     considered one element of the set.  The input must be a 2-D numeric
     matrix to use this argument.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setdiff: XREFsetdiff, *note setxor:
     XREFsetxor, *note ismember: XREFismember.


File: octave.info,  Node: Polynomial Manipulations,  Next: Interpolation,  Prev: Sets,  Up: Top

28 Polynomial Manipulations
***************************

In Octave, a polynomial is represented by its coefficients (arranged in
descending order).  For example, a vector C of length N+1 corresponds to
the following polynomial of order N

     p(x) = C(1) x^N + ... + C(N) x + C(N+1).

* Menu:

* Evaluating Polynomials::
* Finding Roots::
* Products of Polynomials::
* Derivatives / Integrals / Transforms::
* Polynomial Interpolation::
* Miscellaneous Functions::


File: octave.info,  Node: Evaluating Polynomials,  Next: Finding Roots,  Up: Polynomial Manipulations

28.1 Evaluating Polynomials
===========================

The value of a polynomial represented by the vector C can be evaluated
at the point X very easily, as the following example shows:

     N = length (c) - 1;
     val = dot (x.^(N:-1:0), c);

While the above example shows how easy it is to compute the value of a
polynomial, it isn’t the most stable algorithm.  With larger polynomials
you should use more elegant algorithms, such as Horner’s Method, which
is exactly what the Octave function ‘polyval’ does.

   In the case where X is a square matrix, the polynomial given by C is
still well-defined.  As when X is a scalar the obvious implementation is
easily expressed in Octave, but also in this case more elegant
algorithms perform better.  The ‘polyvalm’ function provides such an
algorithm.

 -- : Y = polyval (P, X)
 -- : Y = polyval (P, X, [], MU)
 -- : [Y, DY] = polyval (P, X, S)
 -- : [Y, DY] = polyval (P, X, S, MU)

     Evaluate the polynomial P at the specified values of X.

     If X is a vector or matrix, the polynomial is evaluated for each of
     the elements of X.

     When MU is present, evaluate the polynomial for
     (X - MU(1)) / MU(2).

     In addition to evaluating the polynomial, the second output
     represents the prediction interval, Y +/- DY, which contains at
     least 50% of the future predictions.  To calculate the prediction
     interval, the structured variable S, originating from ‘polyfit’,
     must be supplied.

     See also: *note polyvalm: XREFpolyvalm, *note polyaffine:
     XREFpolyaffine, *note polyfit: XREFpolyfit, *note roots: XREFroots,
     *note poly: XREFpoly.

 -- : polyvalm (C, X)
     Evaluate a polynomial in the matrix sense.

     ‘polyvalm (C, X)’ will evaluate the polynomial in the matrix sense,
     i.e., matrix multiplication is used instead of element by element
     multiplication as used in ‘polyval’.

     The argument X must be a square matrix.

     See also: *note polyval: XREFpolyval, *note roots: XREFroots, *note
     poly: XREFpoly.


File: octave.info,  Node: Finding Roots,  Next: Products of Polynomials,  Prev: Evaluating Polynomials,  Up: Polynomial Manipulations

28.2 Finding Roots
==================

Octave can find the roots of a given polynomial.  This is done by
computing the companion matrix of the polynomial (see the ‘compan’
function for a definition), and then finding its eigenvalues.

 -- : roots (C)

     Compute the roots of the polynomial C.

     For a vector C with N components, return the roots of the
     polynomial

          c(1) * x^(N-1) + ... + c(N-1) * x + c(N)

     As an example, the following code finds the roots of the quadratic
     polynomial

          p(x) = x^2 - 5.

          c = [1, 0, -5];
          roots (c)
          ⇒  2.2361
          ⇒ -2.2361

     Note that the true result is +/- sqrt(5) which is roughly +/-
     2.2361.

     See also: *note poly: XREFpoly, *note compan: XREFcompan, *note
     fzero: XREFfzero.

 -- : Z = polyeig (C0, C1, ..., CL)
 -- : [V, Z] = polyeig (C0, C1, ..., CL)

     Solve the polynomial eigenvalue problem of degree L.

     Given an NxN matrix polynomial

     ‘C(S) = C0 + C1 S + ... + CL S^L’

     ‘polyeig’ solves the eigenvalue problem

     ‘(C0 + C1 Z + ... + CL Z^L) V = 0’.

     Note that the eigenvalues Z are the zeros of the matrix polynomial.
     Z is a row vector with ‘N*L’ elements.  V is a matrix (N x N*L)
     with columns that correspond to the eigenvectors.

     See also: *note eig: XREFeig, *note eigs: XREFeigs, *note compan:
     XREFcompan.

 -- : compan (C)
     Compute the companion matrix corresponding to polynomial
     coefficient vector C.

     The companion matrix is

               _                                                        _
              |  -c(2)/c(1)   -c(3)/c(1)  ...  -c(N)/c(1)  -c(N+1)/c(1)  |
              |       1            0      ...       0             0      |
              |       0            1      ...       0             0      |
          A = |       .            .      .         .             .      |
              |       .            .       .        .             .      |
              |       .            .        .       .             .      |
              |_      0            0      ...       1             0     _|

     The eigenvalues of the companion matrix are equal to the roots of
     the polynomial.

     See also: *note roots: XREFroots, *note poly: XREFpoly, *note eig:
     XREFeig.

 -- : [MULTP, IDXP] = mpoles (P)
 -- : [MULTP, IDXP] = mpoles (P, TOL)
 -- : [MULTP, IDXP] = mpoles (P, TOL, REORDER)
     Identify unique poles in P and their associated multiplicity.

     The output is ordered from largest pole to smallest pole.

     If the relative difference of two poles is less than TOL then they
     are considered to be multiples.  The default value for TOL is
     0.001.

     If the optional parameter REORDER is zero, poles are not sorted.

     The output MULTP is a vector specifying the multiplicity of the
     poles.  ‘MULTP(n)’ refers to the multiplicity of the Nth pole
     ‘P(IDXP(n))’.

     For example:

          p = [2 3 1 1 2];
          [m, n] = mpoles (p)
             ⇒ m = [1; 1; 2; 1; 2]
             ⇒ n = [2; 5; 1; 4; 3]
             ⇒ p(n) = [3, 2, 2, 1, 1]

     See also: *note residue: XREFresidue, *note poly: XREFpoly, *note
     roots: XREFroots, *note conv: XREFconv, *note deconv: XREFdeconv.


File: octave.info,  Node: Products of Polynomials,  Next: Derivatives / Integrals / Transforms,  Prev: Finding Roots,  Up: Polynomial Manipulations

28.3 Products of Polynomials
============================

 -- : conv (A, B)
 -- : conv (A, B, SHAPE)
     Convolve two vectors A and B.

     When A and B are the coefficient vectors of two polynomials, the
     convolution represents the coefficient vector of the product
     polynomial.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

     SHAPE = "full"
          Return the full convolution.  (default) The result is a vector
          with length equal to ‘length (A) + length (B) - 1’.

     SHAPE = "same"
          Return the central part of the convolution with the same size
          as A.

     SHAPE = "valid"
          Return only the parts which do not include zero-padded edges.
          The size of the result is ‘max (size (A) - size (B) + 1, 0)’.

     See also: *note deconv: XREFdeconv, *note conv2: XREFconv2, *note
     convn: XREFconvn, *note fftconv: XREFfftconv.

 -- : C = convn (A, B)
 -- : C = convn (A, B, SHAPE)
     Return the n-D convolution of A and B.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

     SHAPE = "full"
          Return the full convolution.  (default)

     SHAPE = "same"
          Return central part of the convolution with the same size as
          A.  The central part of the convolution begins at the indices
          ‘floor ([size(B)/2] + 1)’.

     SHAPE = "valid"
          Return only the parts which do not include zero-padded edges.
          The size of the result is ‘max (size (A) - size (B) + 1, 0)’.

     See also: *note conv2: XREFconv2, *note conv: XREFconv.

 -- : B = deconv (Y, A)
 -- : [B, R] = deconv (Y, A)
     Deconvolve two vectors (polynomial division).

     ‘[B, R] = deconv (Y, A)’ solves for B and R such that ‘Y = conv (A,
     B) + R’.

     If Y and A are polynomial coefficient vectors, B will contain the
     coefficients of the polynomial quotient and R will be a remainder
     polynomial of lowest order.

     See also: *note conv: XREFconv, *note residue: XREFresidue.

 -- : conv2 (A, B)
 -- : conv2 (V1, V2, M)
 -- : conv2 (..., SHAPE)
     Return the 2-D convolution of A and B.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

     SHAPE = "full"
          Return the full convolution.  (default)

     SHAPE = "same"
          Return the central part of the convolution with the same size
          as A.  The central part of the convolution begins at the
          indices ‘floor ([size(B)/2] + 1)’.

     SHAPE = "valid"
          Return only the parts which do not include zero-padded edges.
          The size of the result is ‘max (size (A) - size (B) + 1, 0)’.

     When the third argument is a matrix, return the convolution of the
     matrix M by the vector V1 in the column direction and by the vector
     V2 in the row direction.

     See also: *note conv: XREFconv, *note convn: XREFconvn.

 -- : Q = polygcd (B, A)
 -- : Q = polygcd (B, A, TOL)

     Find the greatest common divisor of two polynomials.

     This is equivalent to the polynomial found by multiplying together
     all the common roots.  Together with deconv, you can reduce a ratio
     of two polynomials.

     The tolerance TOL defaults to ‘sqrt (eps)’.

     *Caution:* This is a numerically unstable algorithm and should not
     be used on large polynomials.

     Example code:

          polygcd (poly (1:8), poly (3:12)) - poly (3:8)
          ⇒ [ 0, 0, 0, 0, 0, 0, 0 ]
          deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))) - poly (1:2)
          ⇒ [ 0, 0, 0 ]

     See also: *note poly: XREFpoly, *note roots: XREFroots, *note conv:
     XREFconv, *note deconv: XREFdeconv, *note residue: XREFresidue.

 -- : [R, P, K, E] = residue (B, A)
 -- : [B, A] = residue (R, P, K)
 -- : [B, A] = residue (R, P, K, E)
     The first calling form computes the partial fraction expansion for
     the quotient of the polynomials, B and A.

     The quotient is defined as

          B(s)    M       r(m)        N
          ---- = SUM ------------- + SUM k(i)*s^(N-i)
          A(s)   m=1 (s-p(m))^e(m)   i=1

     where M is the number of poles (the length of the R, P, and E), the
     K vector is a polynomial of order N-1 representing the direct
     contribution, and the E vector specifies the multiplicity of the
     m-th residue’s pole.

     For example,

          b = [1, 1, 1];
          a = [1, -5, 8, -4];
          [r, p, k, e] = residue (b, a)
             ⇒ r = [-2; 7; 3]
             ⇒ p = [2; 2; 1]
             ⇒ k = [](0x0)
             ⇒ e = [1; 2; 1]

     which represents the following partial fraction expansion

                  s^2 + s + 1       -2        7        3
             ------------------- = ----- + ------- + -----
             s^3 - 5s^2 + 8s - 4   (s-2)   (s-2)^2   (s-1)

     The second calling form performs the inverse operation and computes
     the reconstituted quotient of polynomials, B(s)/A(s), from the
     partial fraction expansion; represented by the residues, poles, and
     a direct polynomial specified by R, P and K, and the pole
     multiplicity E.

     If the multiplicity, E, is not explicitly specified the
     multiplicity is determined by the function ‘mpoles’.

     For example:

          r = [-2; 7; 3];
          p = [2; 2; 1];
          k = [1, 0];
          [b, a] = residue (r, p, k)
             ⇒ b = [1, -5, 9, -3, 1]
             ⇒ a = [1, -5, 8, -4]

          where mpoles is used to determine e = [1; 2; 1]

     Alternatively the multiplicity may be defined explicitly, for
     example,

          r = [7; 3; -2];
          p = [2; 1; 2];
          k = [1, 0];
          e = [2; 1; 1];
          [b, a] = residue (r, p, k, e)
             ⇒ b = [1, -5, 9, -3, 1]
             ⇒ a = [1, -5, 8, -4]

     which represents the following partial fraction expansion

           -2        7        3         s^4 - 5s^3 + 9s^2 - 3s + 1
          ----- + ------- + ----- + s = --------------------------
          (s-2)   (s-2)^2   (s-1)          s^3 - 5s^2 + 8s - 4

     See also: *note mpoles: XREFmpoles, *note poly: XREFpoly, *note
     roots: XREFroots, *note conv: XREFconv, *note deconv: XREFdeconv.


File: octave.info,  Node: Derivatives / Integrals / Transforms,  Next: Polynomial Interpolation,  Prev: Products of Polynomials,  Up: Polynomial Manipulations

28.4 Derivatives / Integrals / Transforms
=========================================

Octave comes with functions for computing the derivative and the
integral of a polynomial.  The functions ‘polyder’ and ‘polyint’ both
return new polynomials describing the result.  As an example we’ll
compute the definite integral of p(x) = x^2 + 1 from 0 to 3.

     c = [1, 0, 1];
     integral = polyint (c);
     area = polyval (integral, 3) - polyval (integral, 0)
     ⇒ 12

 -- : polyder (P)
 -- : [K] = polyder (A, B)
 -- : [Q, D] = polyder (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by the vector P.

     If a pair of polynomials is given, return the derivative of the
     product A*B.

     If two inputs and two outputs are given, return the derivative of
     the polynomial quotient B/A.  The quotient numerator is in Q and
     the denominator in D.

     See also: *note polyint: XREFpolyint, *note polyval: XREFpolyval,
     *note polyreduce: XREFpolyreduce.

 -- : polyint (P)
 -- : polyint (P, K)
     Return the coefficients of the integral of the polynomial whose
     coefficients are represented by the vector P.

     The variable K is the constant of integration, which by default is
     set to zero.

     See also: *note polyder: XREFpolyder, *note polyval: XREFpolyval.

 -- : polyaffine (F, MU)
     Return the coefficients of the polynomial vector F after an affine
     transformation.

     If F is the vector representing the polynomial f(x), then ‘G =
     polyaffine (F, MU)’ is the vector representing:

          g(x) = f( (x - MU(1)) / MU(2) )

     See also: *note polyval: XREFpolyval, *note polyfit: XREFpolyfit.


File: octave.info,  Node: Polynomial Interpolation,  Next: Miscellaneous Functions,  Prev: Derivatives / Integrals / Transforms,  Up: Polynomial Manipulations

28.5 Polynomial Interpolation
=============================

Octave comes with good support for various kinds of interpolation, most
of which are described in *note Interpolation::.  One simple alternative
to the functions described in the aforementioned chapter, is to fit a
single polynomial, or a piecewise polynomial (spline) to some given data
points.  To avoid a highly fluctuating polynomial, one most often wants
to fit a low-order polynomial to data.  This usually means that it is
necessary to fit the polynomial in a least-squares sense, which just is
what the ‘polyfit’ function does.

 -- : P = polyfit (X, Y, N)
 -- : [P, S] = polyfit (X, Y, N)
 -- : [P, S, MU] = polyfit (X, Y, N)
     Return the coefficients of a polynomial P(X) of degree N that
     minimizes the least-squares-error of the fit to the points ‘[X,
     Y]’.

     If N is a logical vector, it is used as a mask to selectively force
     the corresponding polynomial coefficients to be used or ignored.

     The polynomial coefficients are returned in a row vector.

     The optional output S is a structure containing the following
     fields:

     ‘R’
          Triangular factor R from the QR decomposition.

     ‘X’
          The Vandermonde matrix used to compute the polynomial
          coefficients.

     ‘C’
          The unscaled covariance matrix, formally equal to the inverse
          of X’*X, but computed in a way minimizing roundoff error
          propagation.

     ‘df’
          The degrees of freedom.

     ‘normr’
          The norm of the residuals.

     ‘yf’
          The values of the polynomial for each value of X.

     The second output may be used by ‘polyval’ to calculate the
     statistical error limits of the predicted values.  In particular,
     the standard deviation of P coefficients is given by

     ‘sqrt (diag (s.C)/s.df)*s.normr’.

     When the third output, MU, is present the coefficients, P, are
     associated with a polynomial in

     ‘XHAT = (X - MU(1)) / MU(2)’
     where MU(1) = mean (X), and MU(2) = std (X).

     This linear transformation of X improves the numerical stability of
     the fit.

     See also: *note polyval: XREFpolyval, *note polyaffine:
     XREFpolyaffine, *note roots: XREFroots, *note vander: XREFvander,
     *note zscore: XREFzscore.

   In situations where a single polynomial isn’t good enough, a solution
is to use several polynomials pieced together.  The function ‘splinefit’
fits a piecewise polynomial (spline) to a set of data.

 -- : PP = splinefit (X, Y, BREAKS)
 -- : PP = splinefit (X, Y, P)
 -- : PP = splinefit (..., "periodic", PERIODIC)
 -- : PP = splinefit (..., "robust", ROBUST)
 -- : PP = splinefit (..., "beta", BETA)
 -- : PP = splinefit (..., "order", ORDER)
 -- : PP = splinefit (..., "constraints", CONSTRAINTS)

     Fit a piecewise cubic spline with breaks (knots) BREAKS to the
     noisy data, X and Y.

     X is a vector, and Y is a vector or N-D array.  If Y is an N-D
     array, then X(j) is matched to Y(:,...,:,j).

     P is a positive integer defining the number of intervals along X,
     and P+1 is the number of breaks.  The number of points in each
     interval differ by no more than 1.

     The optional property PERIODIC is a logical value which specifies
     whether a periodic boundary condition is applied to the spline.
     The length of the period is ‘max (BREAKS) - min (BREAKS)’.  The
     default value is ‘false’.

     The optional property ROBUST is a logical value which specifies if
     robust fitting is to be applied to reduce the influence of outlying
     data points.  Three iterations of weighted least squares are
     performed.  Weights are computed from previous residuals.  The
     sensitivity of outlier identification is controlled by the property
     BETA.  The value of BETA is restricted to the range, 0 < BETA < 1.
     The default value is BETA = 1/2.  Values close to 0 give all data
     equal weighting.  Increasing values of BETA reduce the influence of
     outlying data.  Values close to unity may cause instability or rank
     deficiency.

     The fitted spline is returned as a piecewise polynomial, PP, and
     may be evaluated using ‘ppval’.

     The splines are constructed of polynomials with degree ORDER.  The
     default is a cubic, ORDER=3.  A spline with P pieces has P+ORDER
     degrees of freedom.  With periodic boundary conditions the degrees
     of freedom are reduced to P.

     The optional property, CONSTRAINTS, is a structure specifying
     linear constraints on the fit.  The structure has three fields,
     "xc", "yc", and "cc".

     "xc"
          Vector of the x-locations of the constraints.

     "yc"
          Constraining values at the locations XC.  The default is an
          array of zeros.

     "cc"
          Coefficients (matrix).  The default is an array of ones.  The
          number of rows is limited to the order of the piecewise
          polynomials, ORDER.

     Constraints are linear combinations of derivatives of order 0 to
     ORDER-1 according to

          cc(1,j) * y(xc(j)) + cc(2,j) * y'(xc(j)) + ... = yc(:,...,:,j).

     See also: *note interp1: XREFinterp1, *note unmkpp: XREFunmkpp,
     *note ppval: XREFppval, *note spline: XREFspline, *note pchip:
     XREFpchip, *note ppder: XREFppder, *note ppint: XREFppint, *note
     ppjumps: XREFppjumps.

   The number of BREAKS (or knots) used to construct the piecewise
polynomial is a significant factor in suppressing the noise present in
the input data, X and Y.  This is demonstrated by the example below.

     x = 2 * pi * rand (1, 200);
     y = sin (x) + sin (2 * x) + 0.2 * randn (size (x));
     ## Uniform breaks
     breaks = linspace (0, 2 * pi, 41); % 41 breaks, 40 pieces
     pp1 = splinefit (x, y, breaks);
     ## Breaks interpolated from data
     pp2 = splinefit (x, y, 10);  % 11 breaks, 10 pieces
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "41 breaks, 40 pieces", "11 breaks, 10 pieces"})

   The piecewise polynomial fit, provided by ‘splinefit’, has continuous
derivatives up to the ORDER-1.  For example, a cubic fit has continuous
first and second derivatives.  This is demonstrated by the code

     ## Data (200 points)
     x = 2 * pi * rand (1, 200);
     y = sin (x) + sin (2 * x) + 0.1 * randn (size (x));
     ## Piecewise constant
     pp1 = splinefit (x, y, 8, "order", 0);
     ## Piecewise linear
     pp2 = splinefit (x, y, 8, "order", 1);
     ## Piecewise quadratic
     pp3 = splinefit (x, y, 8, "order", 2);
     ## Piecewise cubic
     pp4 = splinefit (x, y, 8, "order", 3);
     ## Piecewise quartic
     pp5 = splinefit (x, y, 8, "order", 4);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     y3 = ppval (pp3, xx);
     y4 = ppval (pp4, xx);
     y5 = ppval (pp5, xx);
     plot (x, y, ".", xx, [y1; y2; y3; y4; y5])
     axis tight
     ylim auto
     legend ({"data", "order 0", "order 1", "order 2", "order 3", "order 4"})

   When the underlying function to provide a fit to is periodic,
‘splinefit’ is able to apply the boundary conditions needed to manifest
a periodic fit.  This is demonstrated by the code below.

     ## Data (100 points)
     x = 2 * pi * [0, (rand (1, 98)), 1];
     y = sin (x) - cos (2 * x) + 0.2 * randn (size (x));
     ## No constraints
     pp1 = splinefit (x, y, 10, "order", 5);
     ## Periodic boundaries
     pp2 = splinefit (x, y, 10, "order", 5, "periodic", true);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "no constraints", "periodic"})

   More complex constraints may be added as well.  For example, the code
below illustrates a periodic fit with values that have been clamped at
the endpoints, and a second periodic fit which is hinged at the
endpoints.

     ## Data (200 points)
     x = 2 * pi * rand (1, 200);
     y = sin (2 * x) + 0.1 * randn (size (x));
     ## Breaks
     breaks = linspace (0, 2 * pi, 10);
     ## Clamped endpoints, y = y' = 0
     xc = [0, 0, 2*pi, 2*pi];
     cc = [(eye (2)), (eye (2))];
     con = struct ("xc", xc, "cc", cc);
     pp1 = splinefit (x, y, breaks, "constraints", con);
     ## Hinged periodic endpoints, y = 0
     con = struct ("xc", 0);
     pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "clamped", "hinged periodic"})

   The ‘splinefit’ function also provides the convenience of a ROBUST
fitting, where the effect of outlying data is reduced.  In the example
below, three different fits are provided.  Two with differing levels of
outlier suppression and a third illustrating the non-robust solution.

     ## Data
     x = linspace (0, 2*pi, 200);
     y = sin (x) + sin (2 * x) + 0.05 * randn (size (x));
     ## Add outliers
     x = [x, linspace(0,2*pi,60)];
     y = [y, -ones(1,60)];
     ## Fit splines with hinged conditions
     con = struct ("xc", [0, 2*pi]);
     ## Robust fitting, beta = 0.25
     pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25);
     ## Robust fitting, beta = 0.75
     pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75);
     ## No robust fitting
     pp3 = splinefit (x, y, 8, "constraints", con);
     ## Plot
     xx = linspace (0, 2*pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     y3 = ppval (pp3, xx);
     plot (x, y, ".", xx, [y1; y2; y3])
     legend ({"data with outliers","robust, beta = 0.25", ...
              "robust, beta = 0.75", "no robust fitting"})
     axis tight
     ylim auto

   A very specific form of polynomial interpretation is the Padé
approximant.  For control systems, a continuous-time delay can be
modeled very simply with the approximant.

 -- : [NUM, DEN] = padecoef (T)
 -- : [NUM, DEN] = padecoef (T, N)
     Compute the Nth-order Padé approximant of the continuous-time delay
     T in transfer function form.

     The Padé approximant of ‘exp (-sT)’ is defined by the following
     equation

                       Pn(s)
          exp (-sT) ~ -------
                       Qn(s)

     Where both Pn(s) and Qn(s) are Nth-order rational functions defined
     by the following expressions

                   N    (2N - k)!N!        k
          Pn(s) = SUM --------------- (-sT)
                  k=0 (2N)!k!(N - k)!

          Qn(s) = Pn(-s)

     The inputs T and N must be non-negative numeric scalars.  If N is
     unspecified it defaults to 1.

     The output row vectors NUM and DEN contain the numerator and
     denominator coefficients in descending powers of s.  Both are
     Nth-order polynomials.

     For example:

          t = 0.1;
          n = 4;
          [num, den] = padecoef (t, n)
          ⇒ num =

                1.0000e-04  -2.0000e-02   1.8000e+00  -8.4000e+01   1.6800e+03

          ⇒ den =

                1.0000e-04   2.0000e-02   1.8000e+00   8.4000e+01   1.6800e+03

   The function, ‘ppval’, evaluates the piecewise polynomials, created
by ‘mkpp’ or other means, and ‘unmkpp’ returns detailed information
about the piecewise polynomial.

   The following example shows how to combine two linear functions and a
quadratic into one function.  Each of these functions is expressed on
adjoined intervals.

     x = [-2, -1, 1, 2];
     p = [ 0,  1, 0;
           1, -2, 1;
           0, -1, 1 ];
     pp = mkpp (x, p);
     xi = linspace (-2, 2, 50);
     yi = ppval (pp, xi);
     plot (xi, yi);

 -- : PP = mkpp (BREAKS, COEFS)
 -- : PP = mkpp (BREAKS, COEFS, D)

     Construct a piecewise polynomial (pp) structure from sample points
     BREAKS and coefficients COEFS.

     BREAKS must be a vector of strictly increasing values.  The number
     of intervals is given by ‘NI = length (BREAKS) - 1’.

     When M is the polynomial order COEFS must be of size:
     NI-by-(M + 1).

     The i-th row of COEFS, ‘COEFS(I,:)’, contains the coefficients for
     the polynomial over the I-th interval, ordered from highest (M) to
     lowest (0) degree.

     COEFS may also be a multi-dimensional array, specifying a
     vector-valued or array-valued polynomial.  In that case the
     polynomial order M is defined by the length of the last dimension
     of COEFS.  The size of first dimension(s) are given by the scalar
     or vector D.  If D is not given it is set to ‘1’.  In this case
     ‘P(R, I, :)’ contains the coefficients for the R-th polynomial
     defined on interval I.  In any case COEFS is reshaped to a 2-D
     matrix of size ‘[NI*prod(D) M]’.

     Programming Note: ‘ppval’ evaluates polynomials at ‘XI -
     BREAKS(i)’, i.e., it subtracts the lower endpoint of the current
     interval from XI.  This must be taken into account when creating
     piecewise polynomials objects with ‘mkpp’.

     See also: *note unmkpp: XREFunmkpp, *note ppval: XREFppval, *note
     spline: XREFspline, *note pchip: XREFpchip, *note ppder: XREFppder,
     *note ppint: XREFppint, *note ppjumps: XREFppjumps.

 -- : [X, P, N, K, D] = unmkpp (PP)

     Extract the components of a piecewise polynomial structure PP.

     This function is the inverse of ‘mkpp’: it extracts the inputs to
     ‘mkpp’ needed to create the piecewise polynomial structure PP.  The
     code below makes this relation explicit:

          [breaks, coefs, numinter, order, dim] = unmkpp (pp);
          pp2  = mkpp (breaks, coefs, dim);

     The piecewise polynomial structure ‘pp2’ obtained in this way, is
     identical to the original ‘pp’.  The same can be obtained by
     directly accessing the fields of the structure ‘pp’.

     The components are:

     X
          Sample points or breaks.

     P
          Polynomial coefficients for points in sample interval.  ‘P(I,
          :)’ contains the coefficients for the polynomial over interval
          I ordered from highest to lowest degree.  If ‘D > 1’, then P
          is a matrix of size ‘[N*prod(D) M]’, where the ‘I + (1:D)’
          rows are the coefficients of all the D polynomials in the
          interval I.

     N
          Number of polynomial pieces or intervals, ‘N = length (X) -
          1’.

     K
          Order of the polynomial plus 1.

     D
          Number of polynomials defined for each interval.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     spline: XREFspline, *note pchip: XREFpchip.

 -- : YI = ppval (PP, XI)
     Evaluate the piecewise polynomial structure PP at the points XI.

     If PP describes a scalar polynomial function, the result is an
     array of the same shape as XI.  Otherwise, the size of the result
     is ‘[pp.dim, length(XI)]’ if XI is a vector, or ‘[pp.dim,
     size(XI)]’ if it is a multi-dimensional array.

     See also: *note mkpp: XREFmkpp, *note unmkpp: XREFunmkpp, *note
     spline: XREFspline, *note pchip: XREFpchip.

 -- : ppd = ppder (pp)
 -- : ppd = ppder (pp, m)
     Compute the piecewise M-th derivative of a piecewise polynomial
     struct PP.

     If M is omitted the first derivative is calculated.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     ppint: XREFppint.

 -- : PPI = ppint (PP)
 -- : PPI = ppint (PP, C)
     Compute the integral of the piecewise polynomial struct PP.

     C, if given, is the constant of integration.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     ppder: XREFppder.

 -- : JUMPS = ppjumps (PP)
     Evaluate the boundary jumps of a piecewise polynomial.

     If there are n intervals, and the dimensionality of PP is d, the
     resulting array has dimensions ‘[d, n-1]’.

     See also: *note mkpp: XREFmkpp.


File: octave.info,  Node: Miscellaneous Functions,  Prev: Polynomial Interpolation,  Up: Polynomial Manipulations

28.6 Miscellaneous Functions
============================

 -- : poly (A)
 -- : poly (X)
     If A is a square N-by-N matrix, ‘poly (A)’ is the row vector of the
     coefficients of ‘det (z * eye (N) - A)’, the characteristic
     polynomial of A.

     For example, the following code finds the eigenvalues of A which
     are the roots of ‘poly (A)’.

          roots (poly (eye (3)))
              ⇒ 1.00001 + 0.00001i
                 1.00001 - 0.00001i
                 0.99999 + 0.00000i

     In fact, all three eigenvalues are exactly 1 which emphasizes that
     for numerical performance the ‘eig’ function should be used to
     compute eigenvalues.

     If X is a vector, ‘poly (X)’ is a vector of the coefficients of the
     polynomial whose roots are the elements of X.  That is, if C is a
     polynomial, then the elements of ‘D = roots (poly (C))’ are
     contained in C.  The vectors C and D are not identical, however,
     due to sorting and numerical errors.

     See also: *note roots: XREFroots, *note eig: XREFeig.

 -- : polyout (C)
 -- : polyout (C, X)
 -- : STR = polyout (...)
     Display a formatted version of the polynomial C.

     The formatted polynomial

          c(x) = c(1) * x^n + ... + c(n) x + c(n+1)

     is returned as a string or written to the screen if ‘nargout’ is
     zero.

     The second argument X specifies the variable name to use for each
     term and defaults to the string "s".

     See also: *note polyreduce: XREFpolyreduce.

 -- : polyreduce (C)
     Reduce a polynomial coefficient vector to a minimum number of terms
     by stripping off any leading zeros.

     See also: *note polyout: XREFpolyout.


File: octave.info,  Node: Interpolation,  Next: Geometry,  Prev: Polynomial Manipulations,  Up: Top

29 Interpolation
****************

* Menu:

* One-dimensional Interpolation::
* Multi-dimensional Interpolation::


File: octave.info,  Node: One-dimensional Interpolation,  Next: Multi-dimensional Interpolation,  Up: Interpolation

29.1 One-dimensional Interpolation
==================================

Octave supports several methods for one-dimensional interpolation, most
of which are described in this section.  *note Polynomial
Interpolation:: and *note Interpolation on Scattered Data:: describe
additional methods.

 -- : YI = interp1 (X, Y, XI)
 -- : YI = interp1 (Y, XI)
 -- : YI = interp1 (..., METHOD)
 -- : YI = interp1 (..., EXTRAP)
 -- : YI = interp1 (..., "left")
 -- : YI = interp1 (..., "right")
 -- : PP = interp1 (..., "pp")

     One-dimensional interpolation.

     Interpolate input data to determine the value of YI at the points
     XI.  If not specified, X is taken to be the indices of Y (‘1:length
     (Y)’).  If Y is a matrix or an N-dimensional array, the
     interpolation is performed on each column of Y.

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "previous"
          Return the previous neighbor.

     "next"
          Return the next neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "pchip"
          Piecewise cubic Hermite interpolating
          polynomial—shape-preserving interpolation with smooth first
          derivative.

     "cubic"
          Cubic interpolation (same as "pchip").

     "spline"
          Cubic spline interpolation—smooth first and second derivatives
          throughout the curve.

     Adding ’*’ to the start of any method above forces ‘interp1’ to
     assume that X is uniformly spaced, and only ‘X(1)’ and ‘X(2)’ are
     referenced.  This is usually faster, and is never slower.  The
     default method is "linear".

     If EXTRAP is the string "extrap", then extrapolate values beyond
     the endpoints using the current METHOD.  If EXTRAP is a number,
     then replace values beyond the endpoints with that number.  When
     unspecified, EXTRAP defaults to ‘NA’.

     If the string argument "pp" is specified, then XI should not be
     supplied and ‘interp1’ returns a piecewise polynomial object.  This
     object can later be used with ‘ppval’ to evaluate the
     interpolation.  There is an equivalence, such that ‘ppval (interp1
     (X, Y, METHOD, "pp"), XI) == interp1 (X, Y, XI, METHOD, "extrap")’.

     Duplicate points in X specify a discontinuous interpolant.  There
     may be at most 2 consecutive points with the same value.  If X is
     increasing, the default discontinuous interpolant is
     right-continuous.  If X is decreasing, the default discontinuous
     interpolant is left-continuous.  The continuity condition of the
     interpolant may be specified by using the options "left" or "right"
     to select a left-continuous or right-continuous interpolant,
     respectively.  Discontinuous interpolation is only allowed for
     "nearest" and "linear" methods; in all other cases, the X-values
     must be unique.

     An example of the use of ‘interp1’ is

          xf = [0:0.05:10];
          yf = sin (2*pi*xf/5);
          xp = [0:10];
          yp = sin (2*pi*xp/5);
          lin = interp1 (xp, yp, xf);
          near = interp1 (xp, yp, xf, "nearest");
          pch = interp1 (xp, yp, xf, "pchip");
          spl = interp1 (xp, yp, xf, "spline");
          plot (xf,yf,"r", xf,near,"g", xf,lin,"b", xf,pch,"c", xf,spl,"m",
                xp,yp,"r*");
          legend ("original", "nearest", "linear", "pchip", "spline");

     See also: *note pchip: XREFpchip, *note spline: XREFspline, *note
     interpft: XREFinterpft, *note interp2: XREFinterp2, *note interp3:
     XREFinterp3, *note interpn: XREFinterpn.

   There are some important differences between the various
interpolation methods.  The "spline" method enforces that both the first
and second derivatives of the interpolated values have a continuous
derivative, whereas the other methods do not.  This means that the
results of the "spline" method are generally smoother.  If the function
to be interpolated is in fact smooth, then "spline" will give excellent
results.  However, if the function to be evaluated is in some manner
discontinuous, then "pchip" interpolation might give better results.

   This can be demonstrated by the code

     t = -2:2;
     dt = 1;
     ti =-2:0.025:2;
     dti = 0.025;
     y = sign (t);
     ys = interp1 (t,y,ti,"spline");
     yp = interp1 (t,y,ti,"pchip");
     ddys = diff (diff (ys)./dti) ./ dti;
     ddyp = diff (diff (yp)./dti) ./ dti;
     figure (1);
     plot (ti,ys,"r-", ti,yp,"g-");
     legend ("spline", "pchip", 4);
     figure (2);
     plot (ti,ddys,"r+", ti,ddyp,"g*");
     legend ("spline", "pchip");

   Fourier interpolation, is a resampling technique where a signal is
converted to the frequency domain, padded with zeros and then
reconverted to the time domain.

 -- : interpft (X, N)
 -- : interpft (X, N, DIM)

     Fourier interpolation.

     If X is a vector then X is resampled with N points.  The data in X
     is assumed to be equispaced.  If X is a matrix or an N-dimensional
     array, the interpolation is performed on each column of X.

     If DIM is specified, then interpolate along the dimension DIM.

     ‘interpft’ assumes that the interpolated function is periodic, and
     so assumptions are made about the endpoints of the interpolation.

     See also: *note interp1: XREFinterp1.

   There are two significant limitations on Fourier interpolation.
First, the function signal is assumed to be periodic, and so
non-periodic signals will be poorly represented at the edges.  Second,
both the signal and its interpolation are required to be sampled at
equispaced points.  An example of the use of ‘interpft’ is

     t = 0 : 0.3 : pi; dt = t(2)-t(1);
     n = length (t); k = 100;
     ti = t(1) + [0 : k-1]*dt*n/k;
     y = sin (4*t + 0.3) .* cos (3*t - 0.1);
     yp = sin (4*ti + 0.3) .* cos (3*ti - 0.1);
     plot (ti, yp, "g", ti, interp1 (t, y, ti, "spline"), "b", ...
           ti, interpft (y, k), "c", t, y, "r+");
     legend ("sin(4t+0.3)cos(3t-0.1)", "spline", "interpft", "data");

which demonstrates the poor behavior of Fourier interpolation for
non-periodic functions.

   In addition, the support functions ‘spline’ and ‘lookup’ that
underlie the ‘interp1’ function can be called directly.

 -- : PP = spline (X, Y)
 -- : YI = spline (X, Y, XI)
     Return the cubic spline interpolant of points X and Y.

     When called with two arguments, return the piecewise polynomial PP
     that may be used with ‘ppval’ to evaluate the polynomial at
     specific points.

     When called with a third input argument, ‘spline’ evaluates the
     spline at the points XI.  The third calling form ‘spline (X, Y,
     XI)’ is equivalent to ‘ppval (spline (X, Y), XI)’.

     The variable X must be a vector of length N.

     Y can be either a vector or array.  If Y is a vector it must have a
     length of either N or ‘N + 2’.  If the length of Y is N, then the
     "not-a-knot" end condition is used.  If the length of Y is ‘N + 2’,
     then the first and last values of the vector Y are the values of
     the first derivative of the cubic spline at the endpoints.

     If Y is an array, then the size of Y must have the form ‘[S1, S2,
     ..., SK, N]’ or ‘[S1, S2, ..., SK, N + 2]’.  The array is reshaped
     internally to a matrix where the leading dimension is given by ‘S1
     * S2 * ... * SK’ and each row of this matrix is then treated
     separately.  Note that this is exactly the opposite of ‘interp1’
     but is done for MATLAB compatibility.

     See also: *note pchip: XREFpchip, *note ppval: XREFppval, *note
     mkpp: XREFmkpp, *note unmkpp: XREFunmkpp.


File: octave.info,  Node: Multi-dimensional Interpolation,  Prev: One-dimensional Interpolation,  Up: Interpolation

29.2 Multi-dimensional Interpolation
====================================

There are three multi-dimensional interpolation functions in Octave,
with similar capabilities.  Methods using Delaunay tessellation are
described in *note Interpolation on Scattered Data::.

 -- : ZI = interp2 (X, Y, Z, XI, YI)
 -- : ZI = interp2 (Z, XI, YI)
 -- : ZI = interp2 (Z, N)
 -- : ZI = interp2 (Z)
 -- : ZI = interp2 (..., METHOD)
 -- : ZI = interp2 (..., METHOD, EXTRAP)

     Two-dimensional interpolation.

     Interpolate reference data X, Y, Z to determine ZI at the
     coordinates XI, YI.  The reference data X, Y can be matrices, as
     returned by ‘meshgrid’, in which case the sizes of X, Y, and Z must
     be equal.  If X, Y are vectors describing a grid then ‘length (X)
     == columns (Z)’ and ‘length (Y) == rows (Z)’.  In either case the
     input data must be strictly monotonic.

     If called without X, Y, and just a single reference data matrix Z,
     the 2-D region ‘X = 1:columns (Z), Y = 1:rows (Z)’ is assumed.
     This saves memory if the grid is regular and the distance between
     points is not important.

     If called with a single reference data matrix Z and a refinement
     value N, then perform interpolation over a grid where each original
     interval has been recursively subdivided N times.  This results in
     ‘2^N-1’ additional points for every interval in the original grid.
     If N is omitted a value of 1 is used.  As an example, the interval
     [0,1] with ‘N==2’ results in a refined interval with points at [0,
     1/4, 1/2, 3/4, 1].

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "pchip"
          Piecewise cubic Hermite interpolating
          polynomial—shape-preserving interpolation with smooth first
          derivative.

     "cubic"
          Cubic interpolation (same as "pchip").

     "spline"
          Cubic spline interpolation—smooth first and second derivatives
          throughout the curve.

     EXTRAP is a scalar number.  It replaces values beyond the endpoints
     with EXTRAP.  Note that if EXTRAP is used, METHOD must be specified
     as well.  If EXTRAP is omitted and the METHOD is "spline", then the
     extrapolated values of the "spline" are used.  Otherwise the
     default EXTRAP value for any other METHOD is "NA".

     See also: *note interp1: XREFinterp1, *note interp3: XREFinterp3,
     *note interpn: XREFinterpn, *note meshgrid: XREFmeshgrid.

 -- : VI = interp3 (X, Y, Z, V, XI, YI, ZI)
 -- : VI = interp3 (V, XI, YI, ZI)
 -- : VI = interp3 (V, N)
 -- : VI = interp3 (V)
 -- : VI = interp3 (..., METHOD)
 -- : VI = interp3 (..., METHOD, EXTRAPVAL)

     Three-dimensional interpolation.

     Interpolate reference data X, Y, Z, V to determine VI at the
     coordinates XI, YI, ZI.  The reference data X, Y, Z can be
     matrices, as returned by ‘meshgrid’, in which case the sizes of X,
     Y, Z, and V must be equal.  If X, Y, Z are vectors describing a
     cubic grid then ‘length (X) == columns (V)’, ‘length (Y) == rows
     (V)’, and ‘length (Z) == size (V, 3)’.  In either case the input
     data must be strictly monotonic.

     If called without X, Y, Z, and just a single reference data matrix
     V, the 3-D region ‘X = 1:columns (V), Y = 1:rows (V), Z = 1:size
     (V, 3)’ is assumed.  This saves memory if the grid is regular and
     the distance between points is not important.

     If called with a single reference data matrix V and a refinement
     value N, then perform interpolation over a 3-D grid where each
     original interval has been recursively subdivided N times.  This
     results in ‘2^N-1’ additional points for every interval in the
     original grid.  If N is omitted a value of 1 is used.  As an
     example, the interval [0,1] with ‘N==2’ results in a refined
     interval with points at [0, 1/4, 1/2, 3/4, 1].

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "cubic"
          Piecewise cubic Hermite interpolating
          polynomial—shape-preserving interpolation with smooth first
          derivative (not implemented yet).

     "spline"
          Cubic spline interpolation—smooth first and second derivatives
          throughout the curve.

     EXTRAPVAL is a scalar number.  It replaces values beyond the
     endpoints with EXTRAPVAL.  Note that if EXTRAPVAL is used, METHOD
     must be specified as well.  If EXTRAPVAL is omitted and the METHOD
     is "spline", then the extrapolated values of the "spline" are used.
     Otherwise the default EXTRAPVAL value for any other METHOD is "NA".

     See also: *note interp1: XREFinterp1, *note interp2: XREFinterp2,
     *note interpn: XREFinterpn, *note meshgrid: XREFmeshgrid.

 -- : VI = interpn (X1, X2, ..., V, Y1, Y2, ...)
 -- : VI = interpn (V, Y1, Y2, ...)
 -- : VI = interpn (V, M)
 -- : VI = interpn (V)
 -- : VI = interpn (..., METHOD)
 -- : VI = interpn (..., METHOD, EXTRAPVAL)

     Perform N-dimensional interpolation, where N is at least two.

     Each element of the N-dimensional array V represents a value at a
     location given by the parameters X1, X2, ..., XN.  The parameters
     X1, X2, ..., XN are either N-dimensional arrays of the same size as
     the array V in the "ndgrid" format or vectors.  The parameters Y1,
     etc. respect a similar format to X1, etc., and they represent the
     points at which the array VI is interpolated.

     If X1, ..., XN are omitted, they are assumed to be ‘x1 = 1 : size
     (V, 1)’, etc.  If M is specified, then the interpolation adds a
     point half way between each of the interpolation points.  This
     process is performed M times.  If only V is specified, then M is
     assumed to be ‘1’.

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "pchip"
          Piecewise cubic Hermite interpolating
          polynomial—shape-preserving interpolation with smooth first
          derivative (not implemented yet).

     "cubic"
          Cubic interpolation (same as "pchip" [not implemented yet]).

     "spline"
          Cubic spline interpolation—smooth first and second derivatives
          throughout the curve.

     The default method is "linear".

     EXTRAPVAL is a scalar number.  It replaces values beyond the
     endpoints with EXTRAPVAL.  Note that if EXTRAPVAL is used, METHOD
     must be specified as well.  If EXTRAPVAL is omitted and the METHOD
     is "spline", then the extrapolated values of the "spline" are used.
     Otherwise the default EXTRAPVAL value for any other METHOD is "NA".

     See also: *note interp1: XREFinterp1, *note interp2: XREFinterp2,
     *note interp3: XREFinterp3, *note spline: XREFspline, *note ndgrid:
     XREFndgrid.

   A significant difference between ‘interpn’ and the other two
multi-dimensional interpolation functions is the fashion in which the
dimensions are treated.  For ‘interp2’ and ‘interp3’, the y-axis is
considered to be the columns of the matrix, whereas the x-axis
corresponds to the rows of the array.  As Octave indexes arrays in
column major order, the first dimension of any array is the columns, and
so ‘interpn’ effectively reverses the ’x’ and ’y’ dimensions.  Consider
the example,

     x = y = z = -1:1;
     f = @(x,y,z) x.^2 - y - z.^2;
     [xx, yy, zz] = meshgrid (x, y, z);
     v = f (xx,yy,zz);
     xi = yi = zi = -1:0.1:1;
     [xxi, yyi, zzi] = meshgrid (xi, yi, zi);
     vi = interp3 (x, y, z, v, xxi, yyi, zzi, "spline");
     [xxi, yyi, zzi] = ndgrid (xi, yi, zi);
     vi2 = interpn (x, y, z, v, xxi, yyi, zzi, "spline");
     mesh (zi, yi, squeeze (vi2(1,:,:)));

where ‘vi’ and ‘vi2’ are identical.  The reversal of the dimensions is
treated in the ‘meshgrid’ and ‘ndgrid’ functions respectively.


File: octave.info,  Node: Geometry,  Next: Signal Processing,  Prev: Interpolation,  Up: Top

30 Geometry
***********

Much of the geometry code in Octave is based on the Qhull library(1).
Some of the documentation for Qhull, particularly for the options that
can be passed to ‘delaunay’, ‘voronoi’ and ‘convhull’, etc., is relevant
to Octave users.

* Menu:

* Delaunay Triangulation::
* Voronoi Diagrams::
* Convex Hull::
* Interpolation on Scattered Data::
* Vector Rotation Matrices::

   ---------- Footnotes ----------

   (1) Barber, C.B., Dobkin, D.P., and Huhdanpaa, H.T., ‘The Quickhull
Algorithm for Convex Hulls’, ACM Trans. on Mathematical Software,
22(4):469–483, Dec 1996, <http://www.qhull.org>


File: octave.info,  Node: Delaunay Triangulation,  Next: Voronoi Diagrams,  Up: Geometry

30.1 Delaunay Triangulation
===========================

The Delaunay triangulation is constructed from a set of circum-circles.
These circum-circles are chosen so that there are at least three of the
points in the set to triangulation on the circumference of the
circum-circle.  None of the points in the set of points falls within any
of the circum-circles.

   In general there are only three points on the circumference of any
circum-circle.  However, in some cases, and in particular for the case
of a regular grid, 4 or more points can be on a single circum-circle.
In this case the Delaunay triangulation is not unique.

 -- : TRI = delaunay (X, Y)
 -- : TETR = delaunay (X, Y, Z)
 -- : TRI = delaunay (X)
 -- : TRI = delaunay (..., OPTIONS)
     Compute the Delaunay triangulation for a 2-D or 3-D set of points.

     For 2-D sets, the return value TRI is a set of triangles which
     satisfies the Delaunay circum-circle criterion, i.e., no data point
     from [X, Y] is within the circum-circle of the defining triangle.
     The set of triangles TRI is a matrix of size [n, 3].  Each row
     defines a triangle and the three columns are the three vertices of
     the triangle.  The value of ‘TRI(i,j)’ is an index into X and Y for
     the location of the j-th vertex of the i-th triangle.

     For 3-D sets, the return value TETR is a set of tetrahedrons which
     satisfies the Delaunay circum-circle criterion, i.e., no data point
     from [X, Y, Z] is within the circum-circle of the defining
     tetrahedron.  The set of tetrahedrons is a matrix of size [n, 4].
     Each row defines a tetrahedron and the four columns are the four
     vertices of the tetrahedron.  The value of ‘TETR(i,j)’ is an index
     into X, Y, Z for the location of the j-th vertex of the i-th
     tetrahedron.

     The input X may also be a matrix with two or three columns where
     the first column contains x-data, the second y-data, and the
     optional third column contains z-data.

     An optional final argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options are ‘{"Qt", "Qbb", "Qc"}’.  If QHull fails for 2-D input
     the triangulation is attempted again with the options ‘{"Qt",
     "Qbb", "Qc", "Qz"}’ which may result in reduced accuracy.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

          x = rand (1, 10);
          y = rand (1, 10);
          tri = delaunay (x, y);
          triplot (tri, x, y);
          hold on;
          plot (x, y, "r*");
          axis ([0,1,0,1]);

     See also: *note delaunayn: XREFdelaunayn, *note convhull:
     XREFconvhull, *note voronoi: XREFvoronoi, *note triplot:
     XREFtriplot, *note trimesh: XREFtrimesh, *note tetramesh:
     XREFtetramesh, *note trisurf: XREFtrisurf.

   For 3-D inputs ‘delaunay’ returns a set of tetrahedra that satisfy
the Delaunay circum-circle criteria.  Similarly, ‘delaunayn’ returns the
N-dimensional simplex satisfying the Delaunay circum-circle criteria.
The N-dimensional extension of a triangulation is called a tessellation.

 -- : T = delaunayn (PTS)
 -- : T = delaunayn (PTS, OPTIONS)
     Compute the Delaunay triangulation for an N-dimensional set of
     points.

     The Delaunay triangulation is a tessellation of the convex hull of
     a set of points such that no N-sphere defined by the N-triangles
     contains any other points from the set.

     The input matrix PTS of size [n, dim] contains n points in a space
     of dimension dim.  The return matrix T has size [m, dim+1].  Each
     row of T contains a set of indices back into the original set of
     points PTS which describes a simplex of dimension dim.  For
     example, a 2-D simplex is a triangle and 3-D simplex is a
     tetrahedron.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options depend on the dimension of the input:

        • 2-D and 3-D: OPTIONS = ‘{"Qt", "Qbb", "Qc"}’

        • 4-D and higher: OPTIONS = ‘{"Qt", "Qbb", "Qc", "Qx"}’

     If QHull fails for 2-D input the triangulation is attempted again
     with the options ‘{"Qt", "Qbb", "Qc", "Qz"}’ which may result in
     reduced accuracy.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     See also: *note delaunay: XREFdelaunay, *note convhulln:
     XREFconvhulln, *note voronoin: XREFvoronoin, *note trimesh:
     XREFtrimesh, *note tetramesh: XREFtetramesh.

   An example of a Delaunay triangulation of a set of points is

     rand ("state", 2);
     x = rand (10, 1);
     y = rand (10, 1);
     T = delaunay (x, y);
     X = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
     Y = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
     axis ([0, 1, 0, 1]);
     plot (X, Y, "b", x, y, "r*");

* Menu:

* Plotting the Triangulation::
* Identifying Points in Triangulation::


File: octave.info,  Node: Plotting the Triangulation,  Next: Identifying Points in Triangulation,  Up: Delaunay Triangulation

30.1.1 Plotting the Triangulation
---------------------------------

Octave has the functions ‘triplot’, ‘trimesh’, and ‘trisurf’ to plot the
Delaunay triangulation of a 2-dimensional set of points.  ‘tetramesh’
will plot the triangulation of a 3-dimensional set of points.

 -- : triplot (TRI, X, Y)
 -- : triplot (TRI, X, Y, LINESPEC)
 -- : H = triplot (...)
     Plot a 2-D triangular mesh.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.

     The linestyle to use for the plot can be defined with the argument
     LINESPEC of the same format as the ‘plot’ command.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note plot: XREFplot, *note trimesh: XREFtrimesh, *note
     trisurf: XREFtrisurf, *note delaunay: XREFdelaunay.

 -- : trimesh (TRI, X, Y, Z, C)
 -- : trimesh (TRI, X, Y, Z)
 -- : trimesh (TRI, X, Y)
 -- : trimesh (..., PROP, VAL, ...)
 -- : H = trimesh (...)
     Plot a 3-D triangular wireframe mesh.

     In contrast to ‘mesh’, which plots a mesh using rectangles,
     ‘trimesh’ plots the mesh using triangles.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.  Z determines the height above the
     plane of each vertex.  If no Z input is given then the triangles
     are plotted as a 2-D figure.

     The color of the trimesh is computed by linearly scaling the Z
     values to fit the range of the current colormap.  Use ‘caxis’
     and/or change the colormap to control the appearance.

     Optionally, the color of the mesh can be specified independently of
     Z by supplying C, which is a vector for colormap data, or a matrix
     with three columns for RGB data.  The number of colors specified in
     C must either equal the number of vertices in Z or the number of
     triangles in TRI.

     Any property/value pairs are passed directly to the underlying
     patch object.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note mesh: XREFmesh, *note tetramesh: XREFtetramesh,
     *note triplot: XREFtriplot, *note trisurf: XREFtrisurf, *note
     delaunay: XREFdelaunay, *note patch: XREFpatch, *note hidden:
     XREFhidden.

 -- : trisurf (TRI, X, Y, Z, C)
 -- : trisurf (TRI, X, Y, Z)
 -- : trisurf (..., PROP, VAL, ...)
 -- : H = trisurf (...)
     Plot a 3-D triangular surface.

     In contrast to ‘surf’, which plots a surface mesh using rectangles,
     ‘trisurf’ plots the mesh using triangles.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.  Z determines the height above the
     plane of each vertex.

     The color of the trisurf is computed by linearly scaling the Z
     values to fit the range of the current colormap.  Use ‘caxis’
     and/or change the colormap to control the appearance.

     Optionally, the color of the mesh can be specified independently of
     Z by supplying C, which is a vector for colormap data, or a matrix
     with three columns for RGB data.  The number of colors specified in
     C must either equal the number of vertices in Z or the number of
     triangles in TRI.  When specifying the color at each vertex the
     triangle will be colored according to the color of the first vertex
     only (see patch documentation and the "FaceColor" property when set
     to "flat").

     Any property/value pairs are passed directly to the underlying
     patch object.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note surf: XREFsurf, *note triplot: XREFtriplot, *note
     trimesh: XREFtrimesh, *note delaunay: XREFdelaunay, *note patch:
     XREFpatch, *note shading: XREFshading.

 -- : tetramesh (T, X)
 -- : tetramesh (T, X, C)
 -- : tetramesh (..., PROPERTY, VAL, ...)
 -- : H = tetramesh (...)
     Display the tetrahedrons defined in the m-by-4 matrix T as 3-D
     patches.

     T is typically the output of a Delaunay triangulation of a 3-D set
     of points.  Every row of T contains four indices into the n-by-3
     matrix X of the vertices of a tetrahedron.  Every row in X
     represents one point in 3-D space.

     The vector C specifies the color of each tetrahedron as an index
     into the current colormap.  The default value is 1:m where m is the
     number of tetrahedrons; the indices are scaled to map to the full
     range of the colormap.  If there are more tetrahedrons than colors
     in the colormap then the values in C are cyclically repeated.

     Calling ‘tetramesh (..., "property", "value", ...)’ passes all
     property/value pairs directly to the patch function as additional
     arguments.

     The optional return value H is a vector of patch handles where each
     handle represents one tetrahedron in the order given by T.  A
     typical use case for H is to turn the respective patch "visible"
     property "on" or "off".

     Type ‘demo tetramesh’ to see examples on using ‘tetramesh’.

     See also: *note trimesh: XREFtrimesh, *note delaunay: XREFdelaunay,
     *note delaunayn: XREFdelaunayn, *note patch: XREFpatch.

   The difference between ‘triplot’, and ‘trimesh’ or ‘trisurf’, is that
the former only plots the 2-dimensional triangulation itself, whereas
the second two plot the value of a function ‘f (X, Y)’.  An example of
the use of the ‘triplot’ function is

     rand ("state", 2)
     x = rand (20, 1);
     y = rand (20, 1);
     tri = delaunay (x, y);
     triplot (tri, x, y);

which plots the Delaunay triangulation of a set of random points in
2-dimensions.


File: octave.info,  Node: Identifying Points in Triangulation,  Prev: Plotting the Triangulation,  Up: Delaunay Triangulation

30.1.2 Identifying Points in Triangulation
------------------------------------------

It is often necessary to identify whether a particular point in the
N-dimensional space is within the Delaunay tessellation of a set of
points in this N-dimensional space, and if so which N-simplex contains
the point and which point in the tessellation is closest to the desired
point.  The functions ‘tsearch’ and ‘dsearch’ perform this function in a
triangulation, and ‘tsearchn’ and ‘dsearchn’ in an N-dimensional
tessellation.

   To identify whether a particular point represented by a vector P
falls within one of the simplices of an N-simplex, we can write the
Cartesian coordinates of the point in a parametric form with respect to
the N-simplex.  This parametric form is called the Barycentric
Coordinates of the point.  If the points defining the N-simplex are
given by N + 1 vectors ‘T(I,:)’, then the Barycentric coordinates
defining the point P are given by

     P = BETA * T

where BETA contains N + 1 values that together as a vector represent the
Barycentric coordinates of the point P.  To ensure a unique solution for
the values of BETA an additional criteria of

     sum (BETA) == 1

is imposed, and we can therefore write the above as

     P - T(end, :) = BETA(1:end-1) * (T(1:end-1, :)
                     - ones (N, 1) * T(end, :)

Solving for BETA we can then write

     BETA(1:end-1) = (P - T(end, :)) /
                     (T(1:end-1, :) - ones (N, 1) * T(end, :))
     BETA(end) = sum (BETA(1:end-1))

which gives the formula for the conversion of the Cartesian coordinates
of the point P to the Barycentric coordinates BETA.  An important
property of the Barycentric coordinates is that for all points in the
N-simplex

     0 <= BETA(I) <= 1

Therefore, the test in ‘tsearch’ and ‘tsearchn’ essentially only needs
to express each point in terms of the Barycentric coordinates of each of
the simplices of the N-simplex and test the values of BETA.  This is
exactly the implementation used in ‘tsearchn’.  ‘tsearch’ is optimized
for 2-dimensions and the Barycentric coordinates are not explicitly
formed.

 -- : IDX = tsearch (X, Y, T, XI, YI)
     Search for the enclosing Delaunay convex hull.

     For ‘T = delaunay (X, Y)’, finds the index in T containing the
     points ‘(XI, YI)’.  For points outside the convex hull, IDX is NaN.

     See also: *note delaunay: XREFdelaunay, *note delaunayn:
     XREFdelaunayn.

 -- : IDX = tsearchn (X, T, XI)
 -- : [IDX, P] = tsearchn (X, T, XI)
     Search for the enclosing Delaunay convex hull.

     For ‘T = delaunayn (X)’, finds the index in T containing the points
     XI.  For points outside the convex hull, IDX is NaN.

     If requested ‘tsearchn’ also returns the Barycentric coordinates P
     of the enclosing triangles.

     See also: *note delaunay: XREFdelaunay, *note delaunayn:
     XREFdelaunayn.

   An example of the use of ‘tsearch’ can be seen with the simple
triangulation

     X = [-1; -1; 1; 1];
     Y = [-1; 1; -1; 1];
     TRI = [1, 2, 3; 2, 3, 4];

consisting of two triangles defined by TRI.  We can then identify which
triangle a point falls in like

     tsearch (X, Y, TRI, -0.5, -0.5)
     ⇒ 1
     tsearch (X, Y, TRI, 0.5, 0.5)
     ⇒ 2

and we can confirm that a point doesn’t lie within one of the triangles
like

     tsearch (X, Y, TRI, 2, 2)
     ⇒ NaN

   The ‘dsearch’ and ‘dsearchn’ find the closest point in a tessellation
to the desired point.  The desired point does not necessarily have to be
in the tessellation, and even if it the returned point of the
tessellation does not have to be one of the vertices of the N-simplex
within which the desired point is found.

 -- : IDX = dsearch (X, Y, TRI, XI, YI)
 -- : IDX = dsearch (X, Y, TRI, XI, YI, S)
     Return the index IDX of the closest point in ‘X, Y’ to the elements
     ‘[XI(:), YI(:)]’.

     The variable S is accepted for compatibility but is ignored.

     See also: *note dsearchn: XREFdsearchn, *note tsearch: XREFtsearch.

 -- : IDX = dsearchn (X, TRI, XI)
 -- : IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- : IDX = dsearchn (X, XI)
 -- : [IDX, D] = dsearchn (...)
     Return the index IDX of the closest point in X to the elements XI.

     If OUTVAL is supplied, then the values of XI that are not contained
     within one of the simplices TRI are set to OUTVAL.  Generally, TRI
     is returned from ‘delaunayn (X)’.

     See also: *note dsearch: XREFdsearch, *note tsearch: XREFtsearch.

   An example of the use of ‘dsearch’, using the above values of X, Y
and TRI is

     dsearch (X, Y, TRI, -2, -2)
     ⇒ 1

   If you wish the points that are outside the tessellation to be
flagged, then ‘dsearchn’ can be used as

     dsearchn ([X, Y], TRI, [-2, -2], NaN)
     ⇒ NaN
     dsearchn ([X, Y], TRI, [-0.5, -0.5], NaN)
     ⇒ 1

where the point outside the tessellation are then flagged with ‘NaN’.


File: octave.info,  Node: Voronoi Diagrams,  Next: Convex Hull,  Prev: Delaunay Triangulation,  Up: Geometry

30.2 Voronoi Diagrams
=====================

A Voronoi diagram or Voronoi tessellation of a set of points S in an
N-dimensional space, is the tessellation of the N-dimensional space such
that all points in ‘V(P)’, a partitions of the tessellation where P is a
member of S, are closer to P than any other point in S.  The Voronoi
diagram is related to the Delaunay triangulation of a set of points, in
that the vertices of the Voronoi tessellation are the centers of the
circum-circles of the simplices of the Delaunay tessellation.

 -- : voronoi (X, Y)
 -- : voronoi (X, Y, OPTIONS)
 -- : voronoi (..., "linespec")
 -- : voronoi (HAX, ...)
 -- : H = voronoi (...)
 -- : [VX, VY] = voronoi (...)
     Plot the Voronoi diagram of points ‘(X, Y)’.

     The Voronoi facets with points at infinity are not drawn.

     The OPTIONS argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.

     If "linespec" is given it is used to set the color and line style
     of the plot.

     If an axes graphics handle HAX is supplied then the Voronoi diagram
     is drawn on the specified axes rather than in a new figure.

     If a single output argument is requested then the Voronoi diagram
     will be plotted and a graphics handle H to the plot is returned.

     [VX, VY] = voronoi (...) returns the Voronoi vertices instead of
     plotting the diagram.

          x = rand (10, 1);
          y = rand (size (x));
          h = convhull (x, y);
          [vx, vy] = voronoi (x, y);
          plot (vx, vy, "-b", x, y, "o", x(h), y(h), "-g");
          legend ("", "points", "hull");

     See also: *note voronoin: XREFvoronoin, *note delaunay:
     XREFdelaunay, *note convhull: XREFconvhull.

 -- : [C, F] = voronoin (PTS)
 -- : [C, F] = voronoin (PTS, OPTIONS)
     Compute N-dimensional Voronoi facets.

     The input matrix PTS of size [n, dim] contains n points in a space
     of dimension dim.

     C contains the points of the Voronoi facets.  The list F contains,
     for each facet, the indices of the Voronoi points.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.

     The default options depend on the dimension of the input:

        • 2-D and 3-D: OPTIONS = ‘{"Qbb"}’

        • 4-D and higher: OPTIONS = ‘{"Qbb", "Qx"}’

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     See also: *note voronoi: XREFvoronoi, *note convhulln:
     XREFconvhulln, *note delaunayn: XREFdelaunayn.

   An example of the use of ‘voronoi’ is

     rand ("state",9);
     x = rand (10,1);
     y = rand (10,1);
     tri = delaunay (x, y);
     [vx, vy] = voronoi (x, y, tri);
     triplot (tri, x, y, "b");
     hold on;
     plot (vx, vy, "r");

   Additional information about the size of the facets of a Voronoi
diagram, and which points of a set of points is in a polygon can be had
with the ‘polyarea’ and ‘inpolygon’ functions respectively.

 -- : polyarea (X, Y)
 -- : polyarea (X, Y, DIM)

     Determine area of a polygon by triangle method.

     The variables X and Y define the vertex pairs, and must therefore
     have the same shape.  They can be either vectors or arrays.  If
     they are arrays then the columns of X and Y are treated separately
     and an area returned for each.

     If the optional DIM argument is given, then ‘polyarea’ works along
     this dimension of the arrays X and Y.

   An example of the use of ‘polyarea’ might be

     rand ("state", 2);
     x = rand (10, 1);
     y = rand (10, 1);
     [c, f] = voronoin ([x, y]);
     af = zeros (size (f));
     for i = 1 : length (f)
       af(i) = polyarea (c (f {i, :}, 1), c (f {i, :}, 2));
     endfor

   Facets of the Voronoi diagram with a vertex at infinity have infinity
area.  A simplified version of ‘polyarea’ for rectangles is available
with ‘rectint’

 -- : AREA = rectint (A, B)
     Compute area or volume of intersection of rectangles or N-D boxes.

     Compute the area of intersection of rectangles in A and rectangles
     in B.  N-dimensional boxes are supported in which case the volume,
     or hypervolume is computed according to the number of dimensions.

     2-dimensional rectangles are defined as ‘[xpos ypos width height]’
     where xpos and ypos are the position of the bottom left corner.
     Higher dimensions are supported where the coordinates for the
     minimum value of each dimension follow the length of the box in
     that dimension, e.g., ‘[xpos ypos zpos kpos ... width height depth
     k_length ...]’.

     Each row of A and B define a rectangle, and if both define multiple
     rectangles, then the output, AREA, is a matrix where the i-th row
     corresponds to the i-th row of a and the j-th column corresponds to
     the j-th row of b.

     See also: *note polyarea: XREFpolyarea.

 -- : IN = inpolygon (X, Y, XV, YV)
 -- : [IN, ON] = inpolygon (X, Y, XV, YV)

     For a polygon defined by vertex points ‘(XV, YV)’, return true if
     the points ‘(X, Y)’ are inside (or on the boundary) of the polygon;
     Otherwise, return false.

     The input variables X and Y, must have the same dimension.

     The optional output ON returns true if the points are exactly on
     the polygon edge, and false otherwise.

     See also: *note delaunay: XREFdelaunay.

   An example of the use of ‘inpolygon’ might be

     randn ("state", 2);
     x = randn (100, 1);
     y = randn (100, 1);
     vx = cos (pi * [-1 : 0.1: 1]);
     vy = sin (pi * [-1 : 0.1 : 1]);
     in = inpolygon (x, y, vx, vy);
     plot (vx, vy, x(in), y(in), "r+", x(!in), y(!in), "bo");
     axis ([-2, 2, -2, 2]);


File: octave.info,  Node: Convex Hull,  Next: Interpolation on Scattered Data,  Prev: Voronoi Diagrams,  Up: Geometry

30.3 Convex Hull
================

The convex hull of a set of points is the minimum convex envelope
containing all of the points.  Octave has the functions ‘convhull’ and
‘convhulln’ to calculate the convex hull of 2-dimensional and
N-dimensional sets of points.

 -- : H = convhull (X, Y)
 -- : H = convhull (X, Y, Z)
 -- : H = convhull (X)
 -- : H = convhull (..., OPTIONS)
 -- : [H, V] = convhull (...)
     Compute the convex hull of a 2-D or 3-D set of points.

     The hull H is a linear index vector into the original set of points
     that specifies which points form the enclosing hull.  For 2-D
     inputs only, the output is ordered in a counterclockwise manner
     around the hull.

     The input X may also be a matrix with two or three columns where
     the first column contains x-data, the second y-data, and the
     optional third column contains z-data.

     An optional final argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     option is ‘{"Qt"}’.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     If the second output V is requested the volume of the enclosing
     convex hull is calculated.

     See also: *note convhulln: XREFconvhulln, *note delaunay:
     XREFdelaunay, *note voronoi: XREFvoronoi.

 -- : H = convhulln (PTS)
 -- : H = convhulln (PTS, OPTIONS)
 -- : [H, V] = convhulln (...)
     Compute the convex hull of the set of points PTS.

     PTS is a matrix of size [n, dim] containing n points in a space of
     dimension dim.

     The hull H is an index vector into the set of points and specifies
     which points form the enclosing hull.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options depend on the dimension of the input:

        • 2D, 3D, 4D: OPTIONS = ‘{"Qt"}’

        • 5D and higher: OPTIONS = ‘{"Qt", "Qx"}’

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     If the second output V is requested the volume of the enclosing
     convex hull is calculated.

     See also: *note convhull: XREFconvhull, *note delaunayn:
     XREFdelaunayn, *note voronoin: XREFvoronoin.

   An example of the use of ‘convhull’ is

     x = -3:0.05:3;
     y = abs (sin (x));
     k = convhull (x, y);
     plot (x(k), y(k), "r-", x, y, "b+");
     axis ([-3.05, 3.05, -0.05, 1.05]);


File: octave.info,  Node: Interpolation on Scattered Data,  Next: Vector Rotation Matrices,  Prev: Convex Hull,  Up: Geometry

30.4 Interpolation on Scattered Data
====================================

An important use of the Delaunay tessellation is that it can be used to
interpolate from scattered data to an arbitrary set of points.  To do
this the N-simplex of the known set of points is calculated with
‘delaunay’ or ‘delaunayn’.  Then the simplices in to which the desired
points are found are identified.  Finally the vertices of the simplices
are used to interpolate to the desired points.  The functions that
perform this interpolation are ‘griddata’, ‘griddata3’ and ‘griddatan’.

 -- : ZI = griddata (X, Y, Z, XI, YI)
 -- : ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- : [XI, YI, ZI] = griddata (...)

     Generate a regular mesh from irregular data using interpolation.

     The function is defined by ‘Z = f (X, Y)’.  Inputs ‘X, Y, Z’ are
     vectors of the same length or ‘X, Y’ are vectors and ‘Z’ is matrix.

     The interpolation points are all ‘(XI, YI)’.  If XI, YI are vectors
     then they are made into a 2-D mesh.

     The interpolation method can be "nearest", "cubic" or "linear".  If
     method is omitted it defaults to "linear".

     See also: *note griddata3: XREFgriddata3, *note griddatan:
     XREFgriddatan, *note delaunay: XREFdelaunay.

 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI)
 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI, METHOD)
 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI, METHOD, OPTIONS)

     Generate a regular mesh from irregular data using interpolation.

     The function is defined by ‘V = f (X, Y, Z)’.  The interpolation
     points are specified by XI, YI, ZI.

     The interpolation method can be "nearest" or "linear".  If method
     is omitted it defaults to "linear".

     The optional argument OPTIONS is passed directly to Qhull when
     computing the Delaunay triangulation used for interpolation.  See
     ‘delaunayn’ for information on the defaults and how to pass
     different values.

     See also: *note griddata: XREFgriddata, *note griddatan:
     XREFgriddatan, *note delaunayn: XREFdelaunayn.

 -- : YI = griddatan (X, Y, XI)
 -- : YI = griddatan (X, Y, XI, METHOD)
 -- : YI = griddatan (X, Y, XI, METHOD, OPTIONS)

     Generate a regular mesh from irregular data using interpolation.

     The function is defined by ‘Y = f (X)’.  The interpolation points
     are all XI.

     The interpolation method can be "nearest" or "linear".  If method
     is omitted it defaults to "linear".

     The optional argument OPTIONS is passed directly to Qhull when
     computing the Delaunay triangulation used for interpolation.  See
     ‘delaunayn’ for information on the defaults and how to pass
     different values.

     See also: *note griddata: XREFgriddata, *note griddata3:
     XREFgriddata3, *note delaunayn: XREFdelaunayn.

   An example of the use of the ‘griddata’ function is

     rand ("state", 1);
     x = 2*rand (1000,1) - 1;
     y = 2*rand (size (x)) - 1;
     z = sin (2*(x.^2+y.^2));
     [xx,yy] = meshgrid (linspace (-1,1,32));
     zz = griddata (x, y, z, xx, yy);
     mesh (xx, yy, zz);

that interpolates from a random scattering of points, to a uniform grid.


File: octave.info,  Node: Vector Rotation Matrices,  Prev: Interpolation on Scattered Data,  Up: Geometry

30.5 Vector Rotation Matrices
=============================

Also included in Octave’s geometry functions are primitive functions to
enable vector rotations in 3-dimensional space.  Separate functions are
provided for rotation about each of the principle axes, X, Y, and Z.
According to Euler’s rotation theorem, any arbitrary rotation, R, of any
vector, P, can be expressed as a product of the three principle
rotations:

     p' = Rp = Rz*Ry*Rx*p

 -- : T = rotx (ANGLE)

     ‘rotx’ returns the 3x3 transformation matrix corresponding to an
     active rotation of the vector about the x-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the y-z plane from the
     positive x side.

     The form of the transformation matrix is:

               | 1      0           0      |
           T = | 0  cos(ANGLE) -sin(ANGLE) |
               | 0  sin(ANGLE)  cos(ANGLE) |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation V = TU.
     For example, a vector, U, pointing along the positive y-axis,
     rotated 90-degrees about the x-axis, will result in a vector
     pointing along the positive z-axis:

          >> u = [0 1 0]'
          u =
             0
             1
             0

          >> T = rotx (90)
          T =
             1.00000   0.00000   0.00000
             0.00000   0.00000  -1.00000
             0.00000   1.00000   0.00000

          >> v = T*u
          v =
             0.00000
             0.00000
             1.00000

     See also: *note roty: XREFroty, *note rotz: XREFrotz.

 -- : T = roty (ANGLE)

     ‘roty’ returns the 3x3 transformation matrix corresponding to an
     active rotation of a vector about the y-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the z-x plane from the
     positive y side.

     The form of the transformation matrix is:

               |  cos(ANGLE)  0  sin(ANGLE) |
           T = |      0       1      0      |
               | -sin(ANGLE)  0  cos(ANGLE) |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation V = TU.
     For example, a vector, U, pointing along the positive z-axis,
     rotated 90-degrees about the y-axis, will result in a vector
     pointing along the positive x-axis:

            >> u = [0 0 1]'
             u =
                0
                0
                1

             >> T = roty (90)
             T =
                0.00000   0.00000   1.00000
                0.00000   1.00000   0.00000
               -1.00000   0.00000   0.00000

             >> v = T*u
             v =
                1.00000
                0.00000
                0.00000

     See also: *note rotx: XREFrotx, *note rotz: XREFrotz.

 -- : T = rotz (ANGLE)

     ‘rotz’ returns the 3x3 transformation matrix corresponding to an
     active rotation of a vector about the z-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the x-y plane from the
     positive z side.

     The form of the transformation matrix is:

               | cos(ANGLE) -sin(ANGLE) 0 |
           T = | sin(ANGLE)  cos(ANGLE) 0 |
               |     0           0      1 |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation V = TU.
     For example, a vector, U, pointing along the positive x-axis,
     rotated 90-degrees about the z-axis, will result in a vector
     pointing along the positive y-axis:

            >> u = [1 0 0]'
             u =
                1
                0
                0

             >> T = rotz (90)
             T =
                0.00000  -1.00000   0.00000
                1.00000   0.00000   0.00000
                0.00000   0.00000   1.00000

             >> v = T*u
             v =
                0.00000
                1.00000
                0.00000

     See also: *note rotx: XREFrotx, *note roty: XREFroty.


File: octave.info,  Node: Signal Processing,  Next: Image Processing,  Prev: Geometry,  Up: Top

31 Signal Processing
********************

This chapter describes the signal processing and fast Fourier transform
functions available in Octave.  Fast Fourier transforms are computed
with the FFTW or FFTPACK libraries depending on how Octave is built.

 -- : fft (X)
 -- : fft (X, N)
 -- : fft (X, N, DIM)
     Compute the discrete Fourier transform of X using a Fast Fourier
     Transform (FFT) algorithm.

     The FFT is calculated along the first non-singleton dimension of
     the array.  Thus if X is a matrix, ‘fft (X)’ computes the FFT for
     each column of X.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of X to use, or an empty matrix
     to specify that its value should be ignored.  If N is larger than
     the dimension along which the FFT is calculated, then X is resized
     and padded with zeros.  Otherwise, if N is smaller than the
     dimension along which the FFT is calculated, then X is truncated.

     If called with three arguments, DIM is an integer specifying the
     dimension of the matrix along which the FFT is performed.

     See also: *note ifft: XREFifft, *note fft2: XREFfft2, *note fftn:
     XREFfftn, *note fftw: XREFfftw.

 -- : ifft (X)
 -- : ifft (X, N)
 -- : ifft (X, N, DIM)
     Compute the inverse discrete Fourier transform of X using a Fast
     Fourier Transform (FFT) algorithm.

     The inverse FFT is calculated along the first non-singleton
     dimension of the array.  Thus if X is a matrix, ‘fft (X)’ computes
     the inverse FFT for each column of X.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of X to use, or an empty matrix
     to specify that its value should be ignored.  If N is larger than
     the dimension along which the inverse FFT is calculated, then X is
     resized and padded with zeros.  Otherwise, if N is smaller than the
     dimension along which the inverse FFT is calculated, then X is
     truncated.

     If called with three arguments, DIM is an integer specifying the
     dimension of the matrix along which the inverse FFT is performed.

     See also: *note fft: XREFfft, *note ifft2: XREFifft2, *note ifftn:
     XREFifftn, *note fftw: XREFfftw.

 -- : fft2 (A)
 -- : fft2 (A, M, N)
     Compute the two-dimensional discrete Fourier transform of A using a
     Fast Fourier Transform (FFT) algorithm.

     The optional arguments M and N may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

     If A is a multi-dimensional matrix, each two-dimensional sub-matrix
     of A is treated separately.

     See also: *note ifft2: XREFifft2, *note fft: XREFfft, *note fftn:
     XREFfftn, *note fftw: XREFfftw.

 -- : ifft2 (A)
 -- : ifft2 (A, M, N)
     Compute the inverse two-dimensional discrete Fourier transform of A
     using a Fast Fourier Transform (FFT) algorithm.

     The optional arguments M and N may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

     If A is a multi-dimensional matrix, each two-dimensional sub-matrix
     of A is treated separately.

     See also: *note fft2: XREFfft2, *note ifft: XREFifft, *note ifftn:
     XREFifftn, *note fftw: XREFfftw.

 -- : fftn (A)
 -- : fftn (A, SIZE)
     Compute the N-dimensional discrete Fourier transform of A using a
     Fast Fourier Transform (FFT) algorithm.

     The optional vector argument SIZE may be used specify the
     dimensions of the array to be used.  If an element of SIZE is
     smaller than the corresponding dimension of A, then the dimension
     of A is truncated prior to performing the FFT.  Otherwise, if an
     element of SIZE is larger than the corresponding dimension then A
     is resized and padded with zeros.

     See also: *note ifftn: XREFifftn, *note fft: XREFfft, *note fft2:
     XREFfft2, *note fftw: XREFfftw.

 -- : ifftn (A)
 -- : ifftn (A, SIZE)
     Compute the inverse N-dimensional discrete Fourier transform of A
     using a Fast Fourier Transform (FFT) algorithm.

     The optional vector argument SIZE may be used specify the
     dimensions of the array to be used.  If an element of SIZE is
     smaller than the corresponding dimension of A, then the dimension
     of A is truncated prior to performing the inverse FFT.  Otherwise,
     if an element of SIZE is larger than the corresponding dimension
     then A is resized and padded with zeros.

     See also: *note fftn: XREFfftn, *note ifft: XREFifft, *note ifft2:
     XREFifft2, *note fftw: XREFfftw.

   Octave uses the FFTW libraries to perform FFT computations.  When
Octave starts up and initializes the FFTW libraries, they read a system
wide file (on a Unix system, it is typically ‘/etc/fftw/wisdom’) that
contains information useful to speed up FFT computations.  This
information is called the _wisdom_.  The system-wide file allows wisdom
to be shared between all applications using the FFTW libraries.

   Use the ‘fftw’ function to generate and save wisdom.  Using the
utilities provided together with the FFTW libraries (‘fftw-wisdom’ on
Unix systems), you can even add wisdom generated by Octave to the
system-wide wisdom file.

 -- : METHOD = fftw ("planner")
 -- : fftw ("planner", METHOD)
 -- : WISDOM = fftw ("dwisdom")
 -- : fftw ("dwisdom", WISDOM)
 -- : fftw ("threads", NTHREADS)
 -- : NTHREADS = fftw ("threads")

     Manage FFTW wisdom data.

     Wisdom data can be used to significantly accelerate the calculation
     of the FFTs, but implies an initial cost in its calculation.  When
     the FFTW libraries are initialized, they read a system wide wisdom
     file (typically in ‘/etc/fftw/wisdom’), allowing wisdom to be
     shared between applications other than Octave.  Alternatively, the
     ‘fftw’ function can be used to import wisdom.  For example,

          WISDOM = fftw ("dwisdom")

     will save the existing wisdom used by Octave to the string WISDOM.
     This string can then be saved to a file and restored using the
     ‘save’ and ‘load’ commands respectively.  This existing wisdom can
     be re-imported as follows

          fftw ("dwisdom", WISDOM)

     If WISDOM is an empty string, then the wisdom used is cleared.

     During the calculation of Fourier transforms further wisdom is
     generated.  The fashion in which this wisdom is generated is also
     controlled by the ‘fftw’ function.  There are five different
     manners in which the wisdom can be treated:

     "estimate"
          Specifies that no run-time measurement of the optimal means of
          calculating a particular is performed, and a simple heuristic
          is used to pick a (probably sub-optimal) plan.  The advantage
          of this method is that there is little or no overhead in the
          generation of the plan, which is appropriate for a Fourier
          transform that will be calculated once.

     "measure"
          In this case a range of algorithms to perform the transform is
          considered and the best is selected based on their execution
          time.

     "patient"
          Similar to "measure", but a wider range of algorithms is
          considered.

     "exhaustive"
          Like "measure", but all possible algorithms that may be used
          to treat the transform are considered.

     "hybrid"
          As run-time measurement of the algorithm can be expensive,
          this is a compromise where "measure" is used for transforms up
          to the size of 8192 and beyond that the "estimate" method is
          used.

     The default method is "estimate".  The current method can be
     queried with

          METHOD = fftw ("planner")

     or set by using

          fftw ("planner", METHOD)

     Note that calculated wisdom will be lost when restarting Octave.
     However, the wisdom data can be reloaded if it is saved to a file
     as described above.  Saved wisdom files should not be used on
     different platforms since they will not be efficient and the point
     of calculating the wisdom is lost.

     The number of threads used for computing the plans and executing
     the transforms can be set with

          fftw ("threads", NTHREADS)

     Note that octave must be compiled with multi-threaded FFTW support
     for this feature.  The number of processors available to the
     current process is used per default.

     See also: *note fft: XREFfft, *note ifft: XREFifft, *note fft2:
     XREFfft2, *note ifft2: XREFifft2, *note fftn: XREFfftn, *note
     ifftn: XREFifftn.

 -- : fftconv (X, Y)
 -- : fftconv (X, Y, N)
     Convolve two vectors using the FFT for computation.

     ‘c = fftconv (X, Y)’ returns a vector of length equal to ‘length
     (X) + length (Y) - 1’.  If X and Y are the coefficient vectors of
     two polynomials, the returned value is the coefficient vector of
     the product polynomial.

     The computation uses the FFT by calling the function ‘fftfilt’.  If
     the optional argument N is specified, an N-point FFT is used.

     See also: *note deconv: XREFdeconv, *note conv: XREFconv, *note
     conv2: XREFconv2.

 -- : fftfilt (B, X)
 -- : fftfilt (B, X, N)
     Filter X with the FIR filter B using the FFT.

     If X is a matrix, filter each column of the matrix.

     Given the optional third argument, N, ‘fftfilt’ uses the
     overlap-add method to filter X with B using an N-point FFT.  The
     FFT size must be an even power of 2 and must be greater than or
     equal to the length of B.  If the specified N does not meet these
     criteria, it is automatically adjusted to the nearest value that
     does.

     See also: *note filter: XREFfilter, *note filter2: XREFfilter2.

 -- : Y = filter (B, A, X)
 -- : [Y, SF] = filter (B, A, X, SI)
 -- : [Y, SF] = filter (B, A, X, [], DIM)
 -- : [Y, SF] = filter (B, A, X, SI, DIM)
     Apply a 1-D digital filter to the data X.

     ‘filter’ returns the solution to the following linear,
     time-invariant difference equation:

           N                   M
          SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k)    for 1<=n<=length(x)
          k=0                 k=0

     where N=length(a)-1 and M=length(b)-1.  The result is calculated
     over the first non-singleton dimension of X or over DIM if
     supplied.

     An equivalent form of the equation is:

                    N                   M
          y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k)  for 1<=n<=length(x)
                   k=1                 k=0

     where c = a/a(1) and d = b/a(1).

     If the fourth argument SI is provided, it is taken as the initial
     state of the system and the final state is returned as SF.  The
     state vector is a column vector whose length is equal to the length
     of the longest coefficient vector minus one.  If SI is not
     supplied, the initial state vector is set to all zeros.

     In terms of the Z Transform, Y is the result of passing the
     discrete-time signal X through a system characterized by the
     following rational system function:

                    M
                   SUM d(k+1) z^(-k)
                   k=0
          H(z) = ---------------------
                      N
                 1 + SUM c(k+1) z^(-k)
                     k=1

     See also: *note filter2: XREFfilter2, *note fftfilt: XREFfftfilt,
     *note freqz: XREFfreqz.

 -- : Y = filter2 (B, X)
 -- : Y = filter2 (B, X, SHAPE)
     Apply the 2-D FIR filter B to X.

     If the argument SHAPE is specified, return an array of the desired
     shape.  Possible values are:

     "full"
          pad X with zeros on all sides before filtering.

     "same"
          unpadded X (default)

     "valid"
          trim X after filtering so edge effects are no included.

     Note this is just a variation on convolution, with the parameters
     reversed and B rotated 180 degrees.

     See also: *note conv2: XREFconv2.

 -- : [H, W] = freqz (B, A, N, "whole")
 -- : [H, W] = freqz (B)
 -- : [H, W] = freqz (B, A)
 -- : [H, W] = freqz (B, A, N)
 -- : H = freqz (B, A, W)
 -- : [H, W] = freqz (..., FS)
 -- : freqz (...)

     Return the complex frequency response H of the rational IIR filter
     whose numerator and denominator coefficients are B and A,
     respectively.

     The response is evaluated at N angular frequencies between 0 and
     2*pi.

     The output value W is a vector of the frequencies.

     If A is omitted, the denominator is assumed to be 1 (this
     corresponds to a simple FIR filter).

     If N is omitted, a value of 512 is assumed.  For fastest
     computation, N should factor into a small number of small primes.

     If the fourth argument, "whole", is omitted the response is
     evaluated at frequencies between 0 and pi.

     ‘freqz (B, A, W)’

     Evaluate the response at the specific frequencies in the vector W.
     The values for W are measured in radians.

     ‘[...] = freqz (..., FS)’

     Return frequencies in Hz instead of radians assuming a sampling
     rate FS.  If you are evaluating the response at specific
     frequencies W, those frequencies should be requested in Hz rather
     than radians.

     ‘freqz (...)’

     Plot the magnitude and phase response of H rather than returning
     them.

     See also: *note freqz_plot: XREFfreqz_plot.

 -- : freqz_plot (W, H)
 -- : freqz_plot (W, H, FREQ_NORM)
     Plot the magnitude and phase response of H.

     If the optional FREQ_NORM argument is true, the frequency vector W
     is in units of normalized radians.  If FREQ_NORM is false, or not
     given, then W is measured in Hertz.

     See also: *note freqz: XREFfreqz.

 -- : sinc (X)
     Compute the sinc function.

     Return sin (pi*x) / (pi*x).

 -- : B = unwrap (X)
 -- : B = unwrap (X, TOL)
 -- : B = unwrap (X, TOL, DIM)

     Unwrap radian phases by adding or subtracting multiples of 2*pi as
     appropriate to remove jumps greater than TOL.

     TOL defaults to pi.

     Unwrap will work along the dimension DIM.  If DIM is unspecified it
     defaults to the first non-singleton dimension.

 -- : [A, B] = arch_fit (Y, X, P, ITER, GAMMA, A0, B0)
     Fit an ARCH regression model to the time series Y using the scoring
     algorithm in Engle’s original ARCH paper.

     The model is

          y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),
          h(t) = a(1) + a(2) * e(t-1)^2 + ... + a(p+1) * e(t-p)^2

     in which e(t) is N(0, h(t)), given a time-series vector Y up to
     time t-1 and a matrix of (ordinary) regressors X up to t.  The
     order of the regression of the residual variance is specified by P.

     If invoked as ‘arch_fit (Y, K, P)’ with a positive integer K, fit
     an ARCH(K, P) process, i.e., do the above with the t-th row of X
     given by

          [1, y(t-1), ..., y(t-k)]

     Optionally, one can specify the number of iterations ITER, the
     updating factor GAMMA, and initial values a0 and b0 for the scoring
     algorithm.

 -- : arch_rnd (A, B, T)
     Simulate an ARCH sequence of length T with AR coefficients B and CH
     coefficients A.

     The result y(t) follows the model

          y(t) = b(1) + b(2) * y(t-1) + ... + b(lb) * y(t-lb+1) + e(t),

     where e(t), given Y up to time t-1, is N(0, h(t)), with

          h(t) = a(1) + a(2) * e(t-1)^2 + ... + a(la) * e(t-la+1)^2

 -- : [PVAL, LM] = arch_test (Y, X, P)
     For a linear regression model

          y = x * b + e

     perform a Lagrange Multiplier (LM) test of the null hypothesis of
     no conditional heteroscedascity against the alternative of CH(P).

     I.e., the model is

          y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),

     given Y up to t-1 and X up to t, e(t) is N(0, h(t)) with

          h(t) = v + a(1) * e(t-1)^2 + ... + a(p) * e(t-p)^2,

     and the null is a(1) == ... == a(p) == 0.

     If the second argument is a scalar integer, k, perform the same
     test in a linear autoregression model of order k, i.e., with

          [1, y(t-1), ..., y(t-K)]

     as the t-th row of X.

     Under the null, LM approximately has a chisquare distribution with
     P degrees of freedom and PVAL is the p-value (1 minus the CDF of
     this distribution at LM) of the test.

     If no output argument is given, the p-value is displayed.

 -- : arma_rnd (A, B, V, T, N)
     Return a simulation of the ARMA model.

     The ARMA model is defined by

          x(n) = a(1) * x(n-1) + ... + a(k) * x(n-k)
               + e(n) + b(1) * e(n-1) + ... + b(l) * e(n-l)

     in which K is the length of vector A, L is the length of vector B
     and E is Gaussian white noise with variance V.  The function
     returns a vector of length T.

     The optional parameter N gives the number of dummy X(I) used for
     initialization, i.e., a sequence of length T+N is generated and
     X(N+1:T+N) is returned.  If N is omitted, N = 100 is used.

 -- : autoreg_matrix (Y, K)
     Given a time series (vector) Y, return a matrix with ones in the
     first column and the first K lagged values of Y in the other
     columns.

     In other words, for T > K, ‘[1, Y(T-1), ..., Y(T-K)]’ is the t-th
     row of the result.

     The resulting matrix may be used as a regressor matrix in
     autoregressions.

 -- : bartlett (M)
     Return the filter coefficients of a Bartlett (triangular) window of
     length M.

     For a definition of the Bartlett window see, e.g., A.V. Oppenheim &
     R. W. Schafer, ‘Discrete-Time Signal Processing’.

 -- : blackman (M)
 -- : blackman (M, "periodic")
 -- : blackman (M, "symmetric")
     Return the filter coefficients of a Blackman window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

     For a definition of the Blackman window, see, e.g., A.V. Oppenheim
     & R. W. Schafer, ‘Discrete-Time Signal Processing’.

 -- : detrend (X, P)
     If X is a vector, ‘detrend (X, P)’ removes the best fit of a
     polynomial of order P from the data X.

     If X is a matrix, ‘detrend (X, P)’ does the same for each column in
     X.

     The second argument P is optional.  If it is not specified, a value
     of 1 is assumed.  This corresponds to removing a linear trend.

     The order of the polynomial can also be given as a string, in which
     case P must be either "constant" (corresponds to ‘P=0’) or "linear"
     (corresponds to ‘P=1’).

     See also: *note polyfit: XREFpolyfit.

 -- : [D, DD] = diffpara (X, A, B)
     Return the estimator D for the differencing parameter of an
     integrated time series.

     The frequencies from [2*pi*a/t, 2*pi*b/T] are used for the
     estimation.  If B is omitted, the interval [2*pi/T, 2*pi*a/T] is
     used.  If both B and A are omitted then a = 0.5 * sqrt (T) and b =
     1.5 * sqrt (T) is used, where T is the sample size.  If X is a
     matrix, the differencing parameter of each column is estimated.

     The estimators for all frequencies in the intervals described above
     is returned in DD.

     The value of D is simply the mean of DD.

     Reference: P.J. Brockwell & R.A. Davis.  ‘Time Series: Theory and
     Methods’.  Springer 1987.

 -- : durbinlevinson (C, OLDPHI, OLDV)
     Perform one step of the Durbin-Levinson algorithm.

     The vector C specifies the autocovariances ‘[gamma_0, ...,
     gamma_t]’ from lag 0 to T, OLDPHI specifies the coefficients based
     on C(T-1) and OLDV specifies the corresponding error.

     If OLDPHI and OLDV are omitted, all steps from 1 to T of the
     algorithm are performed.

 -- : fftshift (X)
 -- : fftshift (X, DIM)
     Perform a shift of the vector X, for use with the ‘fft’ and ‘ifft’
     functions, in order to move the frequency 0 to the center of the
     vector or matrix.

     If X is a vector of N elements corresponding to N time samples
     spaced by dt, then ‘fftshift (fft (X))’ corresponds to frequencies

          f = [ -(ceil((N-1)/2):-1:1), 0, (1:floor((N-1)/2)) ] * df

     where df = 1 / (N * dt).

     If X is a matrix, the same holds for rows and columns.  If X is an
     array, then the same holds along each dimension.

     The optional DIM argument can be used to limit the dimension along
     which the permutation occurs.

     See also: *note ifftshift: XREFifftshift.

 -- : ifftshift (X)
 -- : ifftshift (X, DIM)
     Undo the action of the ‘fftshift’ function.

     For even length X, ‘fftshift’ is its own inverse, but odd lengths
     differ slightly.

     See also: *note fftshift: XREFfftshift.

 -- : fractdiff (X, D)
     Compute the fractional differences (1-L)^d x where L denotes the
     lag-operator and d is greater than -1.

 -- : hamming (M)
 -- : hamming (M, "periodic")
 -- : hamming (M, "symmetric")
     Return the filter coefficients of a Hamming window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

     For a definition of the Hamming window see, e.g., A.V. Oppenheim &
     R. W. Schafer, ‘Discrete-Time Signal Processing’.

 -- : hanning (M)
 -- : hanning (M, "periodic")
 -- : hanning (M, "symmetric")
     Return the filter coefficients of a Hanning window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

     For a definition of the Hanning window see, e.g., A.V. Oppenheim &
     R. W. Schafer, ‘Discrete-Time Signal Processing’.

 -- : hurst (X)
     Estimate the Hurst parameter of sample X via the rescaled range
     statistic.

     If X is a matrix, the parameter is estimated for every column.

 -- : PP = pchip (X, Y)
 -- : YI = pchip (X, Y, XI)
     Return the Piecewise Cubic Hermite Interpolating Polynomial (pchip)
     of points X and Y.

     If called with two arguments, return the piecewise polynomial PP
     that may be used with ‘ppval’ to evaluate the polynomial at
     specific points.

     When called with a third input argument, ‘pchip’ evaluates the
     pchip polynomial at the points XI.  The third calling form is
     equivalent to ‘ppval (pchip (X, Y), XI)’.

     The variable X must be a strictly monotonic vector (either
     increasing or decreasing) of length N.

     Y can be either a vector or array.  If Y is a vector then it must
     be the same length N as X.  If Y is an array then the size of Y
     must have the form ‘[S1, S2, ..., SK, N]’ The array is reshaped
     internally to a matrix where the leading dimension is given by ‘S1
     * S2 * ... * SK’ and each row of this matrix is then treated
     separately.  Note that this is exactly opposite to ‘interp1’ but is
     done for MATLAB compatibility.

     See also: *note spline: XREFspline, *note ppval: XREFppval, *note
     mkpp: XREFmkpp, *note unmkpp: XREFunmkpp.

 -- : [PXX, W] = periodogram (X)
 -- : [PXX, W] = periodogram (X, WIN)
 -- : [PXX, W] = periodogram (X, WIN, NFFT)
 -- : [PXX, F] = periodogram (X, WIN, NFFT, FS)
 -- : [PXX, F] = periodogram (..., "RANGE")
 -- : periodogram (...)
     Return the periodogram (Power Spectral Density) of X.

     The possible inputs are:

     X

          data vector.  If X is real-valued a one-sided spectrum is
          estimated.  If X is complex-valued, or "RANGE" specifies
          "twosided", the full spectrum is estimated.

     WIN
          window weight data.  If window is empty or unspecified a
          default rectangular window is used.  Otherwise, the window is
          applied to the signal (‘X .* WIN’) before computing the
          periodogram.  The window data must be a vector of the same
          length as X.

     NFFT
          number of frequency bins.  The default is 256 or the next
          higher power of 2 greater than the length of X (‘max (256,
          2.^nextpow2 (length (x)))’).  If NFFT is greater than the
          length of the input then X will be zero-padded to the length
          of NFFT.

     FS
          sampling rate.  The default is 1.

     RANGE
          range of spectrum.  "onesided" computes spectrum from
          [0:nfft/2+1].  "twosided" computes spectrum from [0:nfft-1].

     The optional second output W are the normalized angular
     frequencies.  For a one-sided calculation W is in the range [0, pi]
     if NFFT is even and [0, pi) if NFFT is odd.  Similarly, for a
     two-sided calculation W is in the range [0, 2*pi] or [0, 2*pi)
     depending on NFFT.

     If a sampling frequency is specified, FS, then the output
     frequencies F will be in the range [0, FS/2] or [0, FS/2) for
     one-sided calculations.  For two-sided calculations the range will
     be [0, FS).

     When called with no outputs the periodogram is immediately plotted
     in the current figure window.

     See also: *note fft: XREFfft.

 -- : sinetone (FREQ, RATE, SEC, AMPL)
     Return a sinetone of frequency FREQ with a length of SEC seconds at
     sampling rate RATE and with amplitude AMPL.

     The arguments FREQ and AMPL may be vectors of common size.

     The defaults are RATE = 8000, SEC = 1, and AMPL = 64.

     See also: *note sinewave: XREFsinewave.

 -- : sinewave (M, N, D)
     Return an M-element vector with I-th element given by ‘sin (2 * pi
     * (I+D-1) / N)’.

     The default value for D is 0 and the default value for N is M.

     See also: *note sinetone: XREFsinetone.

 -- : spectral_adf (C)
 -- : spectral_adf (C, WIN)
 -- : spectral_adf (C, WIN, B)
     Return the spectral density estimator given a vector of
     autocovariances C, window name WIN, and bandwidth, B.

     The window name, e.g., "triangle" or "rectangle" is used to search
     for a function called ‘WIN_lw’.

     If WIN is omitted, the triangle window is used.

     If B is omitted, ‘1 / sqrt (length (X))’ is used.

     See also: *note spectral_xdf: XREFspectral_xdf.

 -- : spectral_xdf (X)
 -- : spectral_xdf (X, WIN)
 -- : spectral_xdf (X, WIN, B)
     Return the spectral density estimator given a data vector X, window
     name WIN, and bandwidth, B.

     The window name, e.g., "triangle" or "rectangle" is used to search
     for a function called ‘WIN_sw’.

     If WIN is omitted, the triangle window is used.

     If B is omitted, ‘1 / sqrt (length (X))’ is used.

     See also: *note spectral_adf: XREFspectral_adf.

 -- : spencer (X)
     Return Spencer’s 15-point moving average of each column of X.

 -- : Y = stft (X)
 -- : Y = stft (X, WIN_SIZE)
 -- : Y = stft (X, WIN_SIZE, INC)
 -- : Y = stft (X, WIN_SIZE, INC, NUM_COEF)
 -- : Y = stft (X, WIN_SIZE, INC, NUM_COEF, WIN_TYPE)
 -- : [Y, C] = stft (...)
     Compute the short-time Fourier transform of the vector X with
     NUM_COEF coefficients by applying a window of WIN_SIZE data points
     and an increment of INC points.

     Before computing the Fourier transform, one of the following
     windows is applied:

     "hanning"
          win_type = 1

     "hamming"
          win_type = 2

     "rectangle"
          win_type = 3

     The window names can be passed as strings or by the WIN_TYPE
     number.

     The following defaults are used for unspecified arguments: WIN_SIZE
     = 80, INC = 24, NUM_COEF = 64, and WIN_TYPE = 1.

     ‘Y = stft (X, ...)’ returns the absolute values of the Fourier
     coefficients according to the NUM_COEF positive frequencies.

     ‘[Y, C] = stft (X, ...)’ returns the entire STFT-matrix Y and a
     3-element vector C containing the window size, increment, and
     window type, which is needed by the ‘synthesis’ function.

     See also: *note synthesis: XREFsynthesis.

 -- : X = synthesis (Y, C)
     Compute a signal from its short-time Fourier transform Y and a
     3-element vector C specifying window size, increment, and window
     type.

     The values Y and C can be derived by

          [Y, C] = stft (X , ...)

     See also: *note stft: XREFstft.

 -- : [A, V] = yulewalker (C)
     Fit an AR (p)-model with Yule-Walker estimates given a vector C of
     autocovariances ‘[gamma_0, ..., gamma_p]’.

     Returns the AR coefficients, A, and the variance of white noise, V.


File: octave.info,  Node: Image Processing,  Next: Audio Processing,  Prev: Signal Processing,  Up: Top

32 Image Processing
*******************

Since an image is basically a matrix, Octave is a very powerful
environment for processing and analyzing images.  To illustrate how easy
it is to do image processing in Octave, the following example will load
an image, smooth it by a 5-by-5 averaging filter, and compute the
gradient of the smoothed image.

     I = imread ("myimage.jpg");
     S = conv2 (I, ones (5, 5) / 25, "same");
     [Dx, Dy] = gradient (S);

In this example ‘S’ contains the smoothed image, and ‘Dx’ and ‘Dy’
contains the partial spatial derivatives of the image.

* Menu:

* Loading and Saving Images::
* Displaying Images::
* Representing Images::
* Plotting on top of Images::
* Color Conversion::


File: octave.info,  Node: Loading and Saving Images,  Next: Displaying Images,  Up: Image Processing

32.1 Loading and Saving Images
==============================

The first step in most image processing tasks is to load an image into
Octave which is done with the ‘imread’ function.  The ‘imwrite’ function
is the corresponding function for writing images to the disk.

   In summary, most image processing code will follow the structure of
this code

     I = imread ("my_input_image.img");
     J = process_my_image (I);
     imwrite (J, "my_output_image.img");

 -- : [IMG, MAP, ALPHA] = imread (FILENAME)
 -- : [...] = imread (URL)
 -- : [...] = imread (..., EXT)
 -- : [...] = imread (..., IDX)
 -- : [...] = imread (..., PARAM1, VALUE1, ...)
     Read images from various file formats.

     Read an image as a matrix from the file FILENAME or from the online
     resource URL.  If neither is given, but EXT was specified, look for
     a file with the extension EXT.

     The size and class of the output depends on the format of the
     image.  A color image is returned as an MxNx3 matrix.  Grayscale
     and black-and-white images are of size MxN.  Multipage images will
     have an additional 4th dimension.

     The bit depth of the image determines the class of the output:
     "uint8", "uint16", or "single" for grayscale and color, and
     "logical" for black-and-white.  Note that indexed images always
     return the indexes for a colormap, independent of whether MAP is a
     requested output.  To obtain the actual RGB image, use ‘ind2rgb’.
     When more than one indexed image is being read, MAP is obtained
     from the first.  In some rare cases this may be incorrect and
     ‘imfinfo’ can be used to obtain the colormap of each image.

     See the Octave manual for more information in representing images.

     Some file formats, such as TIFF and GIF, are able to store multiple
     images in a single file.  IDX can be a scalar or vector specifying
     the index of the images to read.  By default, Octave will read only
     the first page.

     Depending on the file format, it is possible to configure the
     reading of images with PARAMETER, VALUE pairs.  The following
     options are supported:

     "Frames" or "Index"
          This is an alternative method to specify IDX.  When specifying
          it in this way, its value can also be the string "all".

     "Info"
          This option exists for MATLAB compatibility, but has no
          effect.  For maximum performance when reading multiple images
          from a single file, use the "Index" option.

     "PixelRegion"
          Controls the image region that is read.  The value must be a
          cell array with two arrays of 3 elements ‘{[ROWS], [COLS]}’.
          The elements in the array are the start, increment, and end
          pixel to be read.  If the increment value is omitted it
          defaults to 1.  For example, the following are all equivalent:

               imread (filename, "PixelRegion", {[200 600], [300 700]});
               imread (filename, "PixelRegion", {[200 1 600], [300 1 700]});
               imread (filename)(200:600, 300:700);

     See also: *note imwrite: XREFimwrite, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

 -- : imwrite (IMG, FILENAME)
 -- : imwrite (IMG, FILENAME, EXT)
 -- : imwrite (IMG, MAP, FILENAME)
 -- : imwrite (..., PARAM1, VAL1, ...)
     Write images in various file formats.

     The image IMG can be a binary, grayscale, RGB, or multi-dimensional
     image.  The size and class of IMG should be the same as what should
     be expected when reading it with ‘imread’: the 3rd and 4th
     dimensions reserved for color space, and multiple pages
     respectively.  If it’s an indexed image, the colormap MAP must also
     be specified.

     If EXT is not supplied, the file extension of FILENAME is used to
     determine the format.  The actual supported formats are dependent
     on options made during the build of Octave.  Use ‘imformats’ to
     check the support of the different image formats.

     Depending on the file format, it is possible to configure the
     writing of images with PARAM, VAL pairs.  The following options are
     supported:

     ‘Alpha’
          Alpha (transparency) channel for the image.  This must be a
          matrix with same class, and number of rows and columns of IMG.
          In case of a multipage image, the size of the 4th dimension
          must also match and the third dimension must be a singleton.
          By default, image will be completely opaque.

     ‘Compression’
          Compression to use one the image.  Can be one of the
          following: "none" (default), "bzip", "fax3", "fax4", "jpeg",
          "lzw", "rle", or "deflate".  Note that not all compression
          types are available for all image formats in which it defaults
          to your Magick library.

     ‘DelayTime’
          For formats that accept animations (such as GIF), controls for
          how long a frame is displayed until it moves to the next one.
          The value must be scalar (which will applied to all frames in
          IMG), or a vector of length equal to the number of frames in
          IM.  The value is in seconds, must be between 0 and 655.35,
          and defaults to 0.5.

     ‘DisposalMethod’
          For formats that accept animations (such as GIF), controls
          what happens to a frame before drawing the next one.  Its
          value can be one of the following strings: "doNotSpecify"
          (default); "leaveInPlace"; "restoreBG"; and "restorePrevious",
          or a cell array of those string with length equal to the
          number of frames in IMG.

     ‘LoopCount’
          For formats that accept animations (such as GIF), controls how
          many times the sequence is repeated.  A value of Inf means an
          infinite loop (default), a value of 0 or 1 that the sequence
          is played only once (loops zero times), while a value of 2 or
          above loops that number of times (looping twice means it plays
          the complete sequence 3 times).  This option is ignored when
          there is only a single image at the end of writing the file.

     ‘Quality’
          Set the quality of the compression.  The value should be an
          integer between 0 and 100, with larger values indicating
          higher visual quality and lower compression.  Defaults to 75.

     ‘WriteMode’
          Some file formats, such as TIFF and GIF, are able to store
          multiple images in a single file.  This option specifies if
          IMG should be appended to the file (if it exists) or if a new
          file should be created for it (possibly overwriting an
          existing file).  The value should be the string "Overwrite"
          (default), or "Append".

          Despite this option, the most efficient method of writing a
          multipage image is to pass a 4 dimensional IMG to ‘imwrite’,
          the same matrix that could be expected when using ‘imread’
          with the option "Index" set to "all".

     See also: *note imread: XREFimread, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

 -- : VAL = IMAGE_PATH ()
 -- : OLD_VAL = IMAGE_PATH (NEW_VAL)
 -- : IMAGE_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated
     list of directories in which to search for image files.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     See also: *note EXEC_PATH: XREFEXEC_PATH, *note OCTAVE_HOME:
     XREFOCTAVE_HOME, *note OCTAVE_EXEC_HOME: XREFOCTAVE_EXEC_HOME.

   It is possible to get information about an image file on disk,
without actually reading it into Octave.  This is done using the
‘imfinfo’ function which provides read access to many of the parameters
stored in the header of the image file.

 -- : INFO = imfinfo (FILENAME)
 -- : INFO = imfinfo (URL)
 -- : INFO = imfinfo (..., EXT)
     Read image information from a file.

     ‘imfinfo’ returns a structure containing information about the
     image stored in the file FILENAME.  If there is no file FILENAME,
     and EXT was specified, it will look for a file named FILENAME and
     extension EXT, i.e., a file named FILENAME.EXT.

     The output structure INFO contains the following fields:

     ‘Filename’
          The full name of the image file.

     ‘FileModDate’
          Date of last modification to the file.

     ‘FileSize’
          Number of bytes of the image on disk

     ‘Format’
          Image format (e.g., "jpeg").

     ‘Height’
          Image height in pixels.

     ‘Width’
          Image Width in pixels.

     ‘BitDepth’
          Number of bits per channel per pixel.

     ‘ColorType’
          Image type.  Value is "grayscale", "indexed", "truecolor",
          "CMYK", or "undefined".

     ‘XResolution’
          X resolution of the image.

     ‘YResolution’
          Y resolution of the image.

     ‘ResolutionUnit’
          Units of image resolution.  Value is "Inch", "Centimeter", or
          "undefined".

     ‘DelayTime’
          Time in 1/100ths of a second (0 to 65535) which must expire
          before displaying the next image in an animated sequence.

     ‘LoopCount’
          Number of iterations to loop an animation.

     ‘ByteOrder’
          Endian option for formats that support it.  Value is
          "little-endian", "big-endian", or "undefined".

     ‘Gamma’
          Gamma level of the image.  The same color image displayed on
          two different workstations may look different due to
          differences in the display monitor.

     ‘Quality’
          JPEG/MIFF/PNG compression level.  Value is an integer in the
          range [0 100].

     ‘DisposalMethod’
          Only valid for GIF images, control how successive frames are
          rendered (how the preceding frame is disposed of) when
          creating a GIF animation.  Values can be "doNotSpecify",
          "leaveInPlace", "restoreBG", or "restorePrevious".  For
          non-GIF files, value is an empty string.

     ‘Chromaticities’
          Value is a 1x8 Matrix with the x,y chromaticity values for
          white, red, green, and blue points, in that order.

     ‘Comment’
          Image comment.

     ‘Compression’
          Compression type.  Value can be "none", "bzip", "fax3",
          "fax4", "jpeg", "lzw", "rle", "deflate", "lzma", "jpeg2000",
          "jbig2", "jbig2", or "undefined".

     ‘Colormap’
          Colormap for each image.

     ‘Orientation’
          The orientation of the image with respect to the rows and
          columns.  Value is an integer between 1 and 8 as defined in
          the TIFF 6 specifications, and for MATLAB compatibility.

     ‘Software’
          Name and version of the software or firmware of the camera or
          image input device used to generate the image.

     ‘Make’
          The manufacturer of the recording equipment.  This is the
          manufacture of the DSC, scanner, video digitizer or other
          equipment that generated the image.

     ‘Model’
          The model name or model number of the recording equipment as
          mentioned on the field "Make".

     ‘DateTime’
          The date and time of image creation as defined by the Exif
          standard, i.e., it is the date and time the file was changed.

     ‘ImageDescription’
          The title of the image as defined by the Exif standard.

     ‘Artist’
          Name of the camera owner, photographer or image creator.

     ‘Copyright’
          Copyright notice of the person or organization claiming rights
          to the image.

     ‘DigitalCamera’
          A struct with information retrieved from the Exif tag.

     ‘GPSInfo’
          A struct with geotagging information retrieved from the Exif
          tag.

     See also: *note imread: XREFimread, *note imwrite: XREFimwrite,
     *note imshow: XREFimshow, *note imformats: XREFimformats.

   By default, Octave’s image IO functions (‘imread’, ‘imwrite’, and
‘imfinfo’) use the ‘GraphicsMagick’ library for their operations.  This
means a vast number of image formats is supported but considering the
large amount of image formats in science and its commonly closed nature,
it is impossible to have a library capable of reading them all.  Because
of this, the function ‘imformats’ keeps a configurable list of available
formats, their extensions, and what functions should the image IO
functions use.  This allows one to expand Octave’s image IO capabilities
by creating functions aimed at acting on specific file formats.

   While it would be possible to call the extra functions directly,
properly configuring Octave with ‘imformats’ allows one to keep a
consistent code that is abstracted from file formats.

   It is important to note that a file format is not actually defined by
its file extension and that ‘GraphicsMagick’ is capable to read and
write more file formats than the ones listed by ‘imformats’.  What this
means is that even with an incorrect or missing extension the image may
still be read correctly, and that even unlisted formats are not
necessarily unsupported.

 -- : imformats ()
 -- : FORMATS = imformats (EXT)
 -- : FORMATS = imformats (FORMAT)
 -- : FORMATS = imformats ("add", FORMAT)
 -- : FORMATS = imformats ("remove", EXT)
 -- : FORMATS = imformats ("update", EXT, FORMAT)
 -- : FORMATS = imformats ("factory")
     Manage supported image formats.

     FORMATS is a structure with information about each supported file
     format, or from a specific format EXT, the value displayed on the
     field EXT.  It contains the following fields:

     ext
          The name of the file format.  This may match the file
          extension but Octave will automatically detect the file
          format.

     description
          A long description of the file format.

     isa
          A function handle to confirm if a file is of the specified
          format.

     write
          A function handle to write if a file is of the specified
          format.

     read
          A function handle to open files the specified format.

     info
          A function handle to obtain image information of the specified
          format.

     alpha
          Logical value if format supports alpha channel (transparency
          or matte).

     multipage
          Logical value if format supports multipage (multiple images
          per file).

     It is possible to change the way Octave manages file formats with
     the options "add", "remove", and "update", and supplying a
     structure FORMAT with the required fields.  The option "factory"
     resets the configuration to the default.

     This can be used by Octave packages to extend the image reading
     capabilities Octave, through use of the PKG_ADD and PKG_DEL
     commands.

     See also: *note imfinfo: XREFimfinfo, *note imread: XREFimread,
     *note imwrite: XREFimwrite.


File: octave.info,  Node: Displaying Images,  Next: Representing Images,  Prev: Loading and Saving Images,  Up: Image Processing

32.2 Displaying Images
======================

A natural part of image processing is visualization of an image.  The
most basic function for this is the ‘imshow’ function that shows the
image given in the first input argument.

 -- : imshow (IM)
 -- : imshow (IM, LIMITS)
 -- : imshow (IM, MAP)
 -- : imshow (RGB, ...)
 -- : imshow (FILENAME)
 -- : imshow (..., STRING_PARAM1, VALUE1, ...)
 -- : H = imshow (...)
     Display the image IM, where IM can be a 2-dimensional (grayscale
     image) or a 3-dimensional (RGB image) matrix.

     If LIMITS is a 2-element vector ‘[LOW, HIGH]’, the image is shown
     using a display range between LOW and HIGH.  If an empty matrix is
     passed for LIMITS, the display range is computed as the range
     between the minimal and the maximal value in the image.

     If MAP is a valid color map, the image will be shown as an indexed
     image using the supplied color map.

     If a filename is given instead of an image, the file will be read
     and shown.

     If given, the parameter STRING_PARAM1 has value VALUE1.
     STRING_PARAM1 can be any of the following:

     "displayrange"
          VALUE1 is the display range as described above.

     "colormap"
          VALUE1 is the colormap to use when displaying an indexed
          image.

     "xdata"
          If VALUE1 is a 2-element vector, it must contain horizontal
          image limits in the form [xfirst, xlast], where xfirst and
          xlast are the abscissa of the centers of the corner pixels.
          Otherwise VALUE1 must be a vector and only the first and last
          elements will be used for xfirst and xlast respectively.

     "ydata"
          If VALUE1 is a 2-element vector, it must contain vertical
          image limits in the form [yfirst, ylast], where yfirst and
          ylast are the ordinates of the center of the corner pixels.
          Otherwise VALUE1 must be a vector and only the first and last
          elements will be used for yfirst and ylast respectively.

     The optional return value H is a graphics handle to the image.

     See also: *note image: XREFimage, *note imagesc: XREFimagesc, *note
     colormap: XREFcolormap, *note gray2ind: XREFgray2ind, *note
     rgb2ind: XREFrgb2ind.

 -- : image (IMG)
 -- : image (X, Y, IMG)
 -- : image (..., "PROP", VAL, ...)
 -- : image ("PROP1", VAL1, ...)
 -- : H = image (...)
     Display a matrix as an indexed color image.

     The elements of IMG are indices into the current colormap.

     X and Y are optional 2-element vectors, ‘[min, max]’, which specify
     the coordinates of the centers of the corner pixels.  If a range is
     specified as ‘[max, min]’ then the image will be reversed along
     that axis.  For convenience, X and Y may be specified as N-element
     vectors matching the length of the data in IMG.  However, only the
     first and last elements will be used to determine the axis limits.

     Multiple property/value pairs may be specified for the image
     object, but they must appear in pairs.

     The optional return value H is a graphics handle to the image.

     Implementation Note: The origin (0, 0) for images is located in the
     upper left.  For ordinary plots, the origin is located in the lower
     left.  Octave handles this inversion by plotting the data normally,
     and then reversing the direction of the y-axis by setting the
     ‘ydir’ property to "reverse".  This has implications whenever an
     image and an ordinary plot need to be overlaid.  The recommended
     solution is to display the image and then plot the reversed ydata
     using, for example, ‘flipud (ydata)’.

     Calling Forms: The ‘image’ function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls ‘newplot’ to prepare the
     graphic figure and axes.  When the only inputs to ‘image’ are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.

     Graphic Properties: The full list of properties is documented at
     *note Image Properties::.

     See also: *note imshow: XREFimshow, *note imagesc: XREFimagesc,
     *note colormap: XREFcolormap.

 -- : imagesc (IMG)
 -- : imagesc (X, Y, IMG)
 -- : imagesc (..., CLIMITS)
 -- : imagesc (..., "PROP", VAL, ...)
 -- : imagesc ("PROP1", VAL1, ...)
 -- : imagesc (HAX, ...)
 -- : H = imagesc (...)
     Display a scaled version of the matrix IMG as a color image.

     The colormap is scaled so that the entries of the matrix occupy the
     entire colormap.  If ‘CLIMITS = [LO, HI]’ is given, then that range
     is set to the "clim" of the current axes.

     X and Y are optional 2-element vectors, ‘[min, max]’, which specify
     the coordinates of the centers of the corner pixels.  If a range is
     specified as ‘[max, min]’ then the image will be reversed along
     that axis.  For convenience, X and Y may be specified as N-element
     vectors matching the length of the data in IMG.  However, only the
     first and last elements will be used to determine the image limits.

     The optional return value H is a graphics handle to the image.

     Calling Forms: The ‘imagesc’ function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls ‘newplot’ to prepare the
     graphic figure and axes.  When the only inputs to ‘image’ are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.

     See also: *note image: XREFimage, *note imshow: XREFimshow, *note
     caxis: XREFcaxis.


File: octave.info,  Node: Representing Images,  Next: Plotting on top of Images,  Prev: Displaying Images,  Up: Image Processing

32.3 Representing Images
========================

In general Octave supports four different kinds of images, grayscale
images, RGB images, binary images, and indexed images.  A grayscale
image is represented with an M-by-N matrix in which each element
corresponds to the intensity of a pixel.  An RGB image is represented
with an M-by-N-by-3 array where each 3-vector corresponds to the red,
green, and blue intensities of each pixel.

   The actual meaning of the value of a pixel in a grayscale or RGB
image depends on the class of the matrix.  If the matrix is of class
‘double’ pixel intensities are between 0 and 1, if it is of class
‘uint8’ intensities are between 0 and 255, and if it is of class
‘uint16’ intensities are between 0 and 65535.

   A binary image is an M-by-N matrix of class ‘logical’.  A pixel in a
binary image is black if it is ‘false’ and white if it is ‘true’.

   An indexed image consists of an M-by-N matrix of integers and a
C-by-3 color map.  Each integer corresponds to an index in the color
map, and each row in the color map corresponds to an RGB color.  The
color map must be of class ‘double’ with values between 0 and 1.

   The following convenience functions are available for conversion
between image formats.

 -- : im2double (IMG)
 -- : im2double (IMG, "indexed")
     Convert image to double precision.

     The conversion of IMG to double precision, is dependent on the type
     of input image.  The following input classes are supported:

     ‘uint8, uint16, and int16’
          The range of values from the class is scaled to the interval
          [0 1].

     ‘logical’
          True and false values are assigned a value of 0 and 1
          respectively.

     ‘single’
          Values are cast to double.

     ‘double’
          Returns the same image.

     If IMG is an indexed image, then the second argument should be the
     string "indexed".  If so, then IMG must either be of floating point
     class, or unsigned integer class and it will simply be cast to
     double.  If it is an integer class, a +1 offset is applied.

     See also: *note double: XREFdouble.

 -- : IMG = gray2ind (I)
 -- : IMG = gray2ind (I, N)
 -- : IMG = gray2ind (BW)
 -- : IMG = gray2ind (BW, N)
 -- : [IMG, MAP] = gray2ind (...)
     Convert a grayscale or binary intensity image to an indexed image.

     The indexed image will consist of N different intensity values.  If
     not given N defaults to 64 for grayscale images or 2 for binary
     black and white images.

     The output IMG is of class uint8 if N is less than or equal to 256;
     Otherwise the return class is uint16.

     See also: *note ind2gray: XREFind2gray, *note rgb2ind: XREFrgb2ind.

 -- : I = ind2gray (X, MAP)
     Convert a color indexed image to a grayscale intensity image.

     The image X must be an indexed image which will be converted using
     the colormap MAP.  If MAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map before conversion to grayscale.

     The output I is of the same class as the input X and may be one of
     ‘uint8’, ‘uint16’, ‘single’, or ‘double’.

     Implementation Note: There are several ways of converting colors to
     grayscale intensities.  This functions uses the luminance value
     obtained from ‘rgb2gray’ which is ‘I = 0.299*R + 0.587*G +
     0.114*B’.  Other possibilities include the value component from
     ‘rgb2hsv’ or using a single color channel from ‘ind2rgb’.

     See also: *note gray2ind: XREFgray2ind, *note ind2rgb: XREFind2rgb.

 -- : [X, MAP] = rgb2ind (RGB)
 -- : [X, MAP] = rgb2ind (R, G, B)
     Convert an image in red-green-blue (RGB) color space to an indexed
     image.

     The input image RGB can be specified as a single matrix of size
     MxNx3, or as three separate variables, R, G, and B, its three color
     channels, red, green, and blue.

     It outputs an indexed image X and a colormap MAP to interpret an
     image exactly the same as the input.  No dithering or other form of
     color quantization is performed.  The output class of the indexed
     image X can be uint8, uint16 or double, whichever is required to
     specify the number of unique colors in the image (which will be
     equal to the number of rows in MAP) in order.

     Multi-dimensional indexed images (of size MxNx3xK) are also
     supported, both via a single input (RGB) or its three color
     channels as separate variables.

     See also: *note ind2rgb: XREFind2rgb, *note rgb2hsv: XREFrgb2hsv,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB = ind2rgb (X, MAP)
 -- : [R, G, B] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.

     The image X must be an indexed image which will be converted using
     the colormap MAP.  If MAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map.

     The output may be a single RGB image (MxNx3 matrix where M and N
     are the original image X dimensions, one for each of the red, green
     and blue channels).  Alternatively, the individual red, green, and
     blue color matrices of size MxN may be returned.

     Multi-dimensional indexed images (of size MxNx1xK) are also
     supported.

     See also: *note rgb2ind: XREFrgb2ind, *note ind2gray: XREFind2gray,
     *note hsv2rgb: XREFhsv2rgb.

   Octave also provides tools to produce and work with movie frame
structures.  Those structures encapsulate the image data ("cdata" field)
together with the corresponding colormap ("colormap" field).

 -- : FRAME = getframe ()
 -- : FRAME = getframe (HAX)
 -- : FRAME = getframe (HFIG)
 -- : FRAME = getframe (..., RECT)

     Capture a figure or axes as a movie frame structure.

     Without an argument, capture the current axes excluding ticklabels,
     title, and x/y/zlabels.  The returned structure FRAME has a field
     ‘cdata’, which contains the actual image data in the form of an
     NxMx3 (RGB) uint8 matrix, and a field ‘colormap’ which is provided
     for MATLAB compatibility but is always empty.

     If the first argument HAX is an axes handle, then capture this
     axes, rather than the current axes returned by ‘gca’.

     If the first argument HFIG is a figure handle then the entire
     corresponding figure canvas is captured.

     Finally, if a second argument RECT is provided it must be a
     four-element vector ([left bottom width height]) defining the
     region inside the figure to be captured.  Regardless of the figure
     "units" property, RECT must be defined in *pixels*.

     See also: *note im2frame: XREFim2frame, *note frame2im:
     XREFframe2im, *note movie: XREFmovie.

 -- : movie (MOV)
 -- : movie (MOV, N)
 -- : movie (MOV, N, FPS)
 -- : movie (H, ...)
     Play a movie defined by an array of frame structures.

     The movie MOV must be a struct array of frames with fields "cdata"
     and "colormap", as returned by the ‘getframe’ function.  By default
     all images are displayed once, at 12 fps, in the current axes.

     The optional argument N is a scalar or vector of integers that
     controls the number of times the movie is displayed and which
     particular frames are shown:

     First element:

          N(1) > 0
               Play the movie N(1) times.

          N(1) < 0
               Play the movie ‘abs (N(1)’ times alternatively in forward
               and backward order.

     Other elements (if any):
          Indices of the frames in MOV that will be displayed.

     If the first argument is a handle to a figure or axes H, the movie
     is played in that figure or axes instead of the current axes.

     See also: *note getframe: XREFgetframe, *note im2frame:
     XREFim2frame, *note frame2im: XREFframe2im.

 -- : [X, MAP] = frame2im (FRAME)
     Convert movie frame to indexed image.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images or movies is given when FRAME is a
     struct array.  In such cases, X will be a MxNx1xK or MxNx3xK for
     indexed and RGB movies respectively, with each frame concatenated
     along the 4th dimension.

     See also: *note im2frame: XREFim2frame, *note getframe:
     XREFgetframe.

 -- : im2frame (RGB)
 -- : im2frame (X, MAP)
     Convert image to movie frame.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images is given when each image
     projection, matrix sizes of MxN and MxNx3 for RGB images, is
     concatenated along the fourth dimension.  In such cases, the
     returned value is a struct array.

     See also: *note frame2im: XREFframe2im.

   The ‘colormap’ function is used to change the colormap of the current
axes or figure.

 -- : CMAP = colormap ()
 -- : CMAP = colormap (MAP)
 -- : CMAP = colormap ("default")
 -- : CMAP = colormap (MAP_NAME)
 -- : CMAP = colormap (HAX, ...)
 -- : colormap MAP_NAME
     Query or set the current colormap.

     With no input arguments, ‘colormap’ returns the current color map.

     ‘colormap (MAP)’ sets the current colormap to MAP.  The colormap
     should be an N row by 3 column matrix.  The columns contain red,
     green, and blue intensities respectively.  All entries must be
     between 0 and 1 inclusive.  The new colormap is returned.

     ‘colormap ("default")’ restores the default colormap (the ‘viridis’
     map with 64 entries).  The default colormap is returned.

     The map may also be specified by a string, MAP_NAME, which is the
     name of a function that returns a colormap.

     If the first argument HAX is an axes handle, then the colormap for
     those axes is queried or set.

     For convenience, it is also possible to use this function with the
     command form, ‘colormap MAP_NAME’.

     The list of built-in colormaps is:

     Map         Description
     --------------------------------------------------------------------------
     viridis     default
     jet         colormap traversing blue, cyan, green, yellow, red.
     cubehelix   colormap traversing black, blue, green, red, white with
                 increasing intensity.
     hsv         cyclic colormap traversing Hue, Saturation, Value space.
     rainbow     colormap traversing red, yellow, blue, green, violet.
     ————-       ———————————————————————————————
     hot         colormap traversing black, red, orange, yellow, white.
     cool        colormap traversing cyan, purple, magenta.
     spring      colormap traversing magenta to yellow.
     summer      colormap traversing green to yellow.
     autumn      colormap traversing red, orange, yellow.
     winter      colormap traversing blue to green.
     ————-       ———————————————————————————————
     gray        colormap traversing black to white in shades of gray.
     bone        colormap traversing black, gray-blue, white.
     copper      colormap traversing black to light copper.
     pink        colormap traversing black, gray-pink, white.
     ocean       colormap traversing black, dark-blue, white.
     ————-       ———————————————————————————————
     colorcube   equally spaced colors in RGB color space.
     flag        cyclic 4-color map of red, white, blue, black.
     lines       cyclic colormap with colors from axes "ColorOrder"
                 property.
     prism       cyclic 6-color map of red, orange, yellow, green, blue,
                 violet.
     ————-       ———————————————————————————————
     white       all white colormap (no colors).

     See also: *note viridis: XREFviridis, *note jet: XREFjet, *note
     cubehelix: XREFcubehelix, *note hsv: XREFhsv, *note rainbow:
     XREFrainbow, *note hot: XREFhot, *note cool: XREFcool, *note
     spring: XREFspring, *note summer: XREFsummer, *note autumn:
     XREFautumn, *note winter: XREFwinter, *note gray: XREFgray, *note
     bone: XREFbone, *note copper: XREFcopper, *note pink: XREFpink,
     *note ocean: XREFocean, *note colorcube: XREFcolorcube, *note flag:
     XREFflag, *note lines: XREFlines, *note prism: XREFprism, *note
     white: XREFwhite.

 -- : iscolormap (CMAP)
     Return true if CMAP is a colormap.

     A colormap is a real matrix, of class single or double, with 3
     columns.  Each row represents a single color.  The 3 columns
     contain red, green, and blue intensities respectively.

     All values in a colormap should be in the [0 1] range but this is
     not enforced.  Each function must decide what to do for values
     outside this range.

     See also: *note colormap: XREFcolormap, *note rgbplot: XREFrgbplot.

   The following functions return predefined colormaps, the same that
can be requested by name using the ‘colormap’ function.

 -- : rgbplot (CMAP)
 -- : rgbplot (CMAP, STYLE)
 -- : H = rgbplot (...)
     Plot the components of a colormap.

     Two different STYLEs are available for displaying the CMAP:

     profile (default)
          Plot the RGB line profile of the colormap for each of the
          channels (red, green and blue) with the plot lines colored
          appropriately.  Each line represents the intensity of an RGB
          component across the colormap.

     composite
          Draw the colormap across the X-axis so that the actual index
          colors are visible rather than the individual color
          components.

     The optional return value H is a graphics handle to the created
     plot.

     Run ‘demo rgbplot’ to see an example of ‘rgbplot’ and each style
     option.

     See also: *note colormap: XREFcolormap.

 -- : MAP = autumn ()
 -- : MAP = autumn (N)
     Create color colormap.  This colormap ranges from red through
     orange to yellow.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = bone ()
 -- : MAP = bone (N)
     Create color colormap.  This colormap varies from black to white
     with gray-blue shades.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = colorcube ()
 -- : MAP = colorcube (N)
     Create color colormap.  This colormap is composed of as many
     equally spaced colors (not grays) in the RGB color space as
     possible.

     If there are not a perfect number N of regularly spaced colors then
     the remaining entries in the colormap are gradients of pure red,
     green, blue, and gray.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = cool ()
 -- : MAP = cool (N)
     Create color colormap.  The colormap varies from cyan to magenta.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = copper ()
 -- : MAP = copper (N)
     Create color colormap.  This colormap varies from black to a light
     copper tone.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = cubehelix ()
 -- : MAP = cubehelix (N)
     Create cubehelix colormap.

     This colormap varies from black to white going though blue, green,
     and red tones while maintaining a monotonically increasing
     perception of intensity.  This is achieved by traversing a color
     cube from black to white through a helix, hence the name cubehelix,
     while taking into account the perceived brightness of each channel
     according to the NTSC specifications from 1953.

          rgbplot (cubehelix (256))

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     Reference: Green, D. A., 2011, ‘A colour scheme for the display of
     astronomical intensity images’, Bulletin of the Astronomical
     Society of India, 39, 289.

     See also: *note colormap: XREFcolormap.

 -- : MAP = flag ()
 -- : MAP = flag (N)
     Create color colormap.  This colormap cycles through red, white,
     blue, and black with each index change.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = gray ()
 -- : MAP = gray (N)
     Create gray colormap.  This colormap varies from black to white
     with shades of gray.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = hot ()
 -- : MAP = hot (N)
     Create color colormap.  This colormap ranges from black through
     dark red, red, orange, yellow, to white.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : hsv (N)
     Create color colormap.  This colormap begins with red, changes
     through yellow, green, cyan, blue, and magenta, before returning to
     red.

     It is useful for displaying periodic functions.  The map is
     obtained by linearly varying the hue through all possible values
     while keeping constant maximum saturation and value.  The
     equivalent code is ‘hsv2rgb ([(0:N-1)'/N, ones(N,2)])’.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = jet ()
 -- : MAP = jet (N)
     Create color colormap.  This colormap ranges from dark blue through
     blue, cyan, green, yellow, red, to dark red.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = lines ()
 -- : MAP = lines (N)
     Create color colormap.  This colormap is composed of the list of
     colors in the current axes "ColorOrder" property.  The default is
     blue, orange, yellow, purple, green, light blue, and dark red.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = ocean ()
 -- : MAP = ocean (N)
     Create color colormap.  This colormap varies from black to white
     with shades of blue.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = pink ()
 -- : MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.

     This colormap gives a sepia tone when used on grayscale images.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = prism ()
 -- : MAP = prism (N)
     Create color colormap.  This colormap cycles through red, orange,
     yellow, green, blue and violet with each index change.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = rainbow ()
 -- : MAP = rainbow (N)
     Create color colormap.  This colormap ranges from red through
     orange, yellow, green, blue, to violet.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = spring ()
 -- : MAP = spring (N)
     Create color colormap.  This colormap varies from magenta to
     yellow.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = summer ()
 -- : MAP = summer (N)
     Create color colormap.  This colormap varies from green to yellow.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = viridis ()
 -- : MAP = viridis (N)
     Create color colormap.  This colormap ranges from dark
     purplish-blue through blue, green, to yellow.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = white ()
 -- : MAP = white (N)
     Create color colormap.  This colormap is completely white.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : MAP = winter ()
 -- : MAP = winter (N)
     Create color colormap.  This colormap varies from blue to green.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- : CMAP = contrast (X)
 -- : CMAP = contrast (X, N)
     Return a gray colormap that maximizes the contrast in an image.

     The returned colormap will have N rows.  If N is not defined then
     the size of the current colormap is used.

     See also: *note colormap: XREFcolormap, *note brighten:
     XREFbrighten.

   The following three functions modify the existing colormap rather
than replace it.

 -- : MAP_OUT = brighten (BETA)
 -- : MAP_OUT = brighten (MAP, BETA)
 -- : MAP_OUT = brighten (H, BETA)
 -- : brighten (...)
     Brighten or darken a colormap.

     The argument BETA must be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the colormap.

     If the MAP argument is omitted, the function is applied to the
     current colormap.

     The first argument can also be a valid graphics handle H, in which
     case ‘brighten’ is applied to the colormap associated with this
     handle.

     If no output is specified then the result is written to the current
     colormap.

     See also: *note colormap: XREFcolormap, *note contrast:
     XREFcontrast.

 -- : spinmap ()
 -- : spinmap (T)
 -- : spinmap (T, INC)
 -- : spinmap ("inf")
     Cycle the colormap for T seconds with a color increment of INC.

     Both parameters are optional.  The default cycle time is 5 seconds
     and the default increment is 2.  If the option "inf" is given then
     cycle continuously until ‘Control-C’ is pressed.

     When rotating, the original color 1 becomes color 2, color 2
     becomes color 3, etc.  A positive or negative increment is allowed
     and a higher value of INC will cause faster cycling through the
     colormap.

     See also: *note colormap: XREFcolormap.

 -- : whitebg ()
 -- : whitebg (COLOR)
 -- : whitebg ("none")
 -- : whitebg (HFIG)
 -- : whitebg (HFIG, COLOR)
 -- : whitebg (HFIG, "none")
     Invert the colors in the current color scheme.

     The root properties are also inverted such that all subsequent
     plots will use the new color scheme.

     If the optional argument COLOR is present then the background color
     is set to COLOR rather than inverted.  COLOR may be a string
     representing one of the eight known colors or an RGB triplet.  The
     special string argument "none" restores the plot to the factory
     default colors.

     If the first argument HFIG is a figure handle or list of figure
     handles, then operate on these figures rather than the current
     figure returned by ‘gcf’.  The root properties will not be changed
     unless 0 is in the list of figures.

     Programming Note: ‘whitebg’ operates by changing the color
     properties of the children of the specified figures.  Only objects
     with a single color are affected.  For example, a patch with a
     single "FaceColor" will be changed, but a patch with shading
     ("interp") will not be modified.  For inversion, the new color is
     simply the inversion in RGB space: ‘CNEW = [1-R 1-G 1-B]’.  When a
     color is specified, the axes and figure are set to the new color,
     and the color of child objects are then adjusted to have some
     contrast (visibility) against the new background.

     See also: *note reset: XREFreset, *note get: XREFget, *note set:
     XREFset.

   The following functions can be used to manipulate colormaps.

 -- : [Y, NEWMAP] = cmunique (X, MAP)
 -- : [Y, NEWMAP] = cmunique (RGB)
 -- : [Y, NEWMAP] = cmunique (I)
     Convert an input image X to an output indexed image Y which uses
     the smallest colormap possible NEWMAP.

     When the input is an indexed image (X with colormap MAP) the output
     is a colormap NEWMAP from which any repeated rows have been
     eliminated.  The output image, Y, is the original input image with
     the indices adjusted to match the new, possibly smaller, colormap.

     When the input is an RGB image (an MxNx3 array), the output
     colormap will contain one entry for every unique color in the
     original image.  In the worst case the new map could have as many
     rows as the number of pixels in the original image.

     When the input is a grayscale image I, the output colormap will
     contain one entry for every unique intensity value in the original
     image.  In the worst case the new map could have as many rows as
     the number of pixels in the original image.

     Implementation Details:

     NEWMAP is always an Mx3 matrix, even if the input image is an
     intensity grayscale image I (all three RGB planes are assigned the
     same value).

     The output image is of class uint8 if the size of the new colormap
     is less than or equal to 256.  Otherwise, the output image is of
     class double.

     See also: *note rgb2ind: XREFrgb2ind, *note gray2ind: XREFgray2ind.

 -- : [Y, NEWMAP] = cmpermute (X, MAP)
 -- : [Y, NEWMAP] = cmpermute (X, MAP, INDEX)
     Reorder colors in a colormap.

     When called with only two arguments, ‘cmpermute’ randomly
     rearranges the colormap MAP and returns a new colormap NEWMAP.  It
     also returns the indexed image Y which is the equivalent of the
     original input image X when displayed using NEWMAP.

     When called with an optional third argument the order of colors in
     the new colormap is defined by INDEX.

     *Caution:* INDEX should not have repeated elements or the function
     will fail.


File: octave.info,  Node: Plotting on top of Images,  Next: Color Conversion,  Prev: Representing Images,  Up: Image Processing

32.4 Plotting on top of Images
==============================

If gnuplot is being used to display images it is possible to plot on top
of images.  Since an image is a matrix it is indexed by row and column
values.  The plotting system is, however, based on the traditional (x,
y) system.  To minimize the difference between the two systems Octave
places the origin of the coordinate system in the point corresponding to
the pixel at (1, 1).  So, to plot points given by row and column values
on top of an image, one should simply call ‘plot’ with the column values
as the first argument and the row values as the second.  As an example
the following code generates an image with random intensities between 0
and 1, and shows the image with red circles over pixels with an
intensity above 0.99.

     I = rand (100, 100);
     [row, col] = find (I > 0.99);
     hold ("on");
     imshow (I);
     plot (col, row, "ro");
     hold ("off");


File: octave.info,  Node: Color Conversion,  Prev: Plotting on top of Images,  Up: Image Processing

32.5 Color Conversion
=====================

Octave supports conversion from the RGB color system to the HSV color
system and vice versa.  It is also possible to convert from a color RGB
image to a grayscale image.

 -- : HSV_MAP = rgb2hsv (RGB_MAP)
 -- : HSV_IMG = rgb2hsv (RGB_IMG)
     Transform a colormap or image from RGB to HSV color space.

     A color in the RGB space consists of red, green, and blue
     intensities.

     A color in HSV space is represented by hue, saturation and value
     (brightness) levels in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     Output class and size will be the same as input.

     See also: *note hsv2rgb: XREFhsv2rgb, *note rgb2ind: XREFrgb2ind,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB_MAP = hsv2rgb (HSV_MAP)
 -- : RGB_IMG = hsv2rgb (HSV_IMG)
     Transform a colormap or image from HSV to RGB color space.

     A color in HSV space is represented by hue, saturation and value
     (brightness) levels in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     The input can be both a colormap or RGB image.  In the case of
     floating point input, values are expected to be on the [0 1] range.
     In the case of hue (azimuth), since the value corresponds to an
     angle, ‘mod (h, 1)’ is used.

          >> hsv2rgb ([0.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([2.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([3.5 1 1])
          ⇒ ans = 0 1 1

     Output class and size will be the same as input.

     See also: *note rgb2hsv: XREFrgb2hsv, *note ind2rgb: XREFind2rgb.

 -- : I = rgb2gray (RGB_IMG)
 -- : GRAY_MAP = rgb2gray (RGB_MAP)
     Transform an image or colormap from red-green-blue (RGB) color
     space to a grayscale intensity image.

     The input may be of class uint8, int8, uint16, int16, single, or
     double.  The output is of the same class as the input.

     Implementation Note: The grayscale intensity is calculated as

          I = 0.298936*R + 0.587043*G + 0.114021*B

     which corresponds to the luminance channel when RGB is translated
     to YIQ as documented in <https://en.wikipedia.org/wiki/YIQ>.

     See also: *note rgb2hsv: XREFrgb2hsv, *note rgb2ind: XREFrgb2ind.


File: octave.info,  Node: Audio Processing,  Next: Object Oriented Programming,  Prev: Image Processing,  Up: Top

33 Audio Processing
*******************

* Menu:

* Audio File Utilities::
* Audio Device Information::
* Audio Player::
* Audio Recorder::
* Audio Data Processing::


File: octave.info,  Node: Audio File Utilities,  Next: Audio Device Information,  Up: Audio Processing

33.1 Audio File Utilities
=========================

The following functions allow you to read, write and retrieve
information about audio files.  Various formats are supported including
wav, flac and ogg vorbis.

 -- : INFO = audioinfo (FILENAME)
     Return information about an audio file specified by FILENAME.

     The output INFO is a structure containing the following fields:

     ‘Filename’
          Name of the audio file.

     ‘CompressionMethod’
          Audio compression method.  Unused, only present for
          compatibility with MATLAB.

     ‘NumChannels’
          Number of audio channels.

     ‘SampleRate’
          Sample rate of the audio, in Hertz.

     ‘TotalSamples’
          Number of samples in the file.

     ‘Duration’
          Duration of the audio, in seconds.

     ‘BitsPerSample’
          Number of bits per sample.

     ‘BitRate’
          Audio bit rate.  Unused, only present for compatibility with
          MATLAB.

     ‘Title’
          "Title" audio metadata value as a string, or empty if not
          present.

     ‘Artist’
          "Artist" audio metadata value as a string, or empty if not
          present.

     ‘Comment’
          "Comment" audio metadata value as a string, or empty if not
          present.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.

 -- : [Y, FS] = audioread (FILENAME)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES)

 -- : [Y, FS] = audioread (FILENAME, DATATYPE)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES, DATATYPE)
     Read the audio file FILENAME and return the audio data Y and
     sampling rate FS.

     The audio data is stored as matrix with rows corresponding to audio
     frames and columns corresponding to channels.

     The optional two-element vector argument SAMPLES specifies starting
     and ending frames.

     The optional argument DATATYPE specifies the datatype to return.
     If it is "native", then the type of data depends on how the data is
     stored in the audio file.

     See also: *note audiowrite: XREFaudiowrite, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audiowrite (FILENAME, Y, FS)
 -- : audiowrite (FILENAME, Y, FS, NAME, VALUE, ...)

     Write audio data from the matrix Y to FILENAME at sampling rate FS
     with the file format determined by the file extension.

     Additional name/value argument pairs may be used to specify the
     following options:

     ‘BitsPerSample’
          Number of bits per sample.  Valid values are 8, 16, 24, and
          32.  Default is 16.

     ‘BitRate’
          Valid argument name, but ignored.  Left for compatibility with
          MATLAB.

     ‘Quality’
          Quality setting for the Ogg Vorbis compressor.  Values can
          range between 0 and 100 with 100 being the highest quality
          setting.  Default is 75.

     ‘Title’
          Title for the audio file.

     ‘Artist’
          Artist name.

     ‘Comment’
          Comment.

     See also: *note audioread: XREFaudioread, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audioformats ()
 -- : audioformats (FORMAT)
     Display information about all supported audio formats.

     If the optional argument FORMAT is given, then display only formats
     with names that start with FORMAT.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.


File: octave.info,  Node: Audio Device Information,  Next: Audio Player,  Prev: Audio File Utilities,  Up: Audio Processing

33.2 Audio Device Information
=============================

 -- : DEVINFO = audiodevinfo ()

 -- : DEVS = audiodevinfo (IO)
 -- : NAME = audiodevinfo (IO, ID)
 -- : ID = audiodevinfo (IO, NAME)
 -- : DRIVERVERSION = audiodevinfo (IO, ID, "DriverVersion")
 -- : ID = audiodevinfo (IO, RATE, BITS, CHANS)
 -- : SUPPORTS = audiodevinfo (IO, ID, RATE, BITS, CHANS)

     Return a structure describing the available audio input and output
     devices.

     The DEVINFO structure has two fields "input" and "output".  The
     value of each field is a structure array with fields "Name",
     "DriverVersion" and "ID" describing an audio device.

     If the optional argument IO is 1, return information about input
     devices only.  If it is 0, return information about output devices
     only.  If IO is the only argument supplied, return the number of
     input or output devices available.

     If the optional argument ID is provided, return information about
     the corresponding device.

     If the optional argument NAME is provided, return the ID of the
     named device.

     If the optional argument "DriverVersion" is given, return the name
     of the driver for the specified device.

     Given a sampling rate, bits per sample, and number of channels for
     an input or output device, return the ID of the first device that
     supports playback or recording using the specified parameters.

     If also given a device ID, return true if the device supports
     playback or recording using those parameters.


File: octave.info,  Node: Audio Player,  Next: Audio Recorder,  Prev: Audio Device Information,  Up: Audio Processing

33.3 Audio Player
=================

The following methods are used to create and use audioplayer objects.
These objects can be used to play back audio data stored in Octave
matrices and arrays.  The audioplayer object supports playback from
various devices available to the system, blocking and non-blocking
playback, convenient pausing and resuming and much more.

 -- : PLAYER = audioplayer (Y, FS)
 -- : PLAYER = audioplayer (Y, FS, NBITS)
 -- : PLAYER = audioplayer (Y, FS, NBITS, ID)
 -- : PLAYER = audioplayer (RECORDER)
 -- : PLAYER = audioplayer (RECORDER, ID)
     Create an audioplayer object that will play back data Y at sample
     rate FS.

     The optional arguments NBITS, and ID specify the bit depth and
     player device id, respectively.  Device IDs may be found using the
     audiodevinfo function.  Given an audioplayer object, use the data
     from the object to initialize the player.

     The signal Y can be a vector or a two-dimensional array.

     The following example will create an audioplayer object that will
     play back one second of white noise at 44100 sample rate using 8
     bits per sample.

          y = 0.25 * randn (2, 44100);
          player = audioplayer (y, 44100, 8);
          play (player);

* Menu:

* Playback::
* Player Properties::


File: octave.info,  Node: Playback,  Next: Player Properties,  Up: Audio Player

33.3.1 Playback
---------------

The following methods are used to control player playback.

 -- : play (PLAYER)
 -- : play (PLAYER, START)
 -- : play (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER without
     blocking.

     Given optional argument start, begin playing at START samples in
     the recording.  Given a two-element vector LIMITS, begin and end
     playing at the number of samples specified by the elements of the
     vector.

 -- : playblocking (PLAYER)
 -- : playblocking (PLAYER, START)
 -- : playblocking (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER with blocking.

     Given optional argument start, begin playing at START samples in
     the recording.  Given a two-element vector LIMITS, begin and end
     playing at the number of samples specified by the elements of the
     vector.

 -- : pause (PLAYER)
     Pause the audioplayer PLAYER.

 -- : resume (PLAYER)
     Resume playback for the paused audioplayer object PLAYER.

 -- : stop (PLAYER)
     Stop the playback for the audioplayer PLAYER and reset the relevant
     variables to their starting values.

 -- : isplaying (PLAYER)
     Return true if the audioplayer object PLAYER is currently playing
     back audio and false otherwise.


File: octave.info,  Node: Player Properties,  Prev: Playback,  Up: Audio Player

33.3.2 Properties
-----------------

The remaining couple of methods are used to get and set various
properties of the audioplayer object.

 -- : VALUE = get (PLAYER, NAME)
 -- : VALUES = get (PLAYER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array return the values of the properties
     identified by the elements of the cell array.  Given only the
     player object, return a scalar structure with values of all
     properties of PLAYER.  The field names of the structure correspond
     to property names.

 -- : set (PLAYER, NAME, VALUE)
 -- : set (PLAYER, PROPERTIES)
 -- : PROPERTIES = set (PLAYER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays, set each property to the
     corresponding value.  Given a structure of PROPERTIES with fields
     corresponding to property names, set the value of those properties
     to the field values.  Given only the audioplayer object, return a
     structure of settable properties.


File: octave.info,  Node: Audio Recorder,  Next: Audio Data Processing,  Prev: Audio Player,  Up: Audio Processing

33.4 Audio Recorder
===================

The following methods are used to create and use audiorecorder objects.
These objects can be used to record audio data from various devices
available to the system.  You can use convenient methods to retrieve
that data or audioplayer objects created from that data.  Methods for
blocking and non-blocking recording, pausing and resuming recording and
much more is available.

 -- : RECORDER = audiorecorder ()
 -- : RECORDER = audiorecorder (FS, NBITS, CHANNELS)
 -- : RECORDER = audiorecorder (FS, NBITS, CHANNELS, ID)
     Create an audiorecorder object recording 8 bit mono audio at 8000
     Hz sample rate.

     The optional arguments FS, NBITS, CHANNELS, and ID specify the
     sample rate, bit depth, number of channels and recording device id,
     respectively.  Device IDs may be found using the audiodevinfo
     function.

* Menu:

* Recording::
* Data Retrieval::
* Recorder Properties::


File: octave.info,  Node: Recording,  Next: Data Retrieval,  Up: Audio Recorder

33.4.1 Recording
----------------

The following methods control the recording process.

 -- : record (RECORDER)
 -- : record (RECORDER, LENGTH)
     Record audio without blocking using the audiorecorder object
     RECORDER until stopped or paused by the STOP or PAUSE method.

     Given the optional argument LENGTH, record for LENGTH seconds.

 -- : recordblocking (RECORDER, LENGTH)
     Record audio with blocking (synchronous I/O).

     The length of the recording in seconds (LENGTH) must be specified.

 -- : pause (RECORDER)
     Pause recording with audiorecorder object RECORDER.

 -- : resume (RECORDER)
     Resume recording with the paused audiorecorder object RECORDER.

 -- : stop (RECORDER)
     Stop the audiorecorder object RECORDER and clean up any audio
     streams.

 -- : isrecording (RECORDER)
     Return true if the audiorecorder object RECORDER is currently
     recording audio and false otherwise.


File: octave.info,  Node: Data Retrieval,  Next: Recorder Properties,  Prev: Recording,  Up: Audio Recorder

33.4.2 Data Retrieval
---------------------

The following methods allow you to retrieve recorded audio data in
various ways.

 -- : DATA = getaudiodata (RECORDER)
 -- : DATA = getaudiodata (RECORDER, DATATYPE)
     Return recorder audio data as a matrix with values between -1.0 and
     1.0 and with as many columns as there are channels in the recorder.

     Given the optional argument DATATYPE, convert the recorded data to
     the specified type, which may be one of "double", "single",
     "int16", "int8" or "uint8".

 -- : PLAYER = getplayer (RECORDER)
     Return an audioplayer object with data recorded by the
     audiorecorder object RECORDER.

 -- : PLAYER = play (RECORDER)
 -- : PLAYER = play (RECORDER, START)
 -- : PLAYER = play (RECORDER, [START, END])
     Play the audio recorded in RECORDER and return a corresponding
     audioplayer object.

     If the optional argument START is provided, begin playing START
     seconds in to the recording.

     If the optional argument END is provided, stop playing at END
     seconds in the recording.


File: octave.info,  Node: Recorder Properties,  Prev: Data Retrieval,  Up: Audio Recorder

33.4.3 Properties
-----------------

The remaining two methods allow you to read or alter the properties of
audiorecorder objects.

 -- : VALUE = get (RECORDER, NAME)
 -- : VALUES = get (RECORDER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array, return the values of the properties
     corresponding to the elements of the cell array.  Given only the
     recorder object, return a scalar structure with values of all
     properties of RECORDER.  The field names of the structure
     correspond to property names.

 -- : set (RECORDER, NAME, VALUE)
 -- : set (RECORDER, PROPERTIES)
 -- : PROPERTIES = set (RECORDER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays of the same size, set each
     property to a corresponding value.  Given a structure with fields
     corresponding to property names, set the value of those properties
     to the corresponding field values.  Given only the recorder object,
     return a structure of settable properties.


File: octave.info,  Node: Audio Data Processing,  Prev: Audio Recorder,  Up: Audio Processing

33.5 Audio Data Processing
==========================

Octave provides a few functions for dealing with audio data.  An audio
‘sample’ is a single output value from an A/D converter, i.e., a small
integer number (usually 8 or 16 bits), and audio data is just a series
of such samples.  It can be characterized by three parameters: the
sampling rate (measured in samples per second or Hz, e.g., 8000 or
44100), the number of bits per sample (e.g., 8 or 16), and the number of
channels (1 for mono, 2 for stereo, etc.).

   There are many different formats for representing such data.
Currently, only the two most popular, _linear encoding_ and _mu-law
encoding_, are supported by Octave.  There is an excellent FAQ on audio
formats by Guido van Rossum <guido@cwi.nl> which can be found at any FAQ
ftp site, in particular in the directory
‘/pub/usenet/news.answers/audio-fmts’ of the archive site
‘rtfm.mit.edu’.

   Octave simply treats audio data as vectors of samples (non-mono data
are not supported yet).  It is assumed that audio files using linear
encoding have one of the extensions ‘lin’ or ‘raw’, and that files
holding data in mu-law encoding end in ‘au’, ‘mu’, or ‘snd’.

 -- : Y = lin2mu (X, N)
     Convert audio data from linear to mu-law.

     Mu-law values use 8-bit unsigned integers.  Linear values use N-bit
     signed integers or floating point values in the range -1 ≤ X ≤ 1 if
     N is 0.

     If N is not specified it defaults to 0, 8, or 16 depending on the
     range of values in X.

     See also: *note mu2lin: XREFmu2lin.

 -- : Y = mu2lin (X, N)
     Convert audio data from mu-law to linear.

     Mu-law values are 8-bit unsigned integers.  Linear values use N-bit
     signed integers or floating point values in the range -1 ≤ Y ≤ 1 if
     N is 0.

     If N is not specified it defaults to 0.

     See also: *note lin2mu: XREFlin2mu.

 -- : record (SEC)
 -- : record (SEC, FS)
     Record SEC seconds of audio from the system’s default audio input
     at a sampling rate of 8000 samples per second.

     If the optional argument FS is given, it specifies the sampling
     rate for recording.

     For more control over audio recording, use the ‘audiorecorder’
     class.

     See also: *note sound: XREFsound, *note soundsc: XREFsoundsc.

 -- : sound (Y)
 -- : sound (Y, FS)
 -- : sound (Y, FS, NBITS)
     Play audio data Y at sample rate FS to the default audio device.

     The audio signal Y can be a vector or a two-column array,
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note soundsc: XREFsoundsc, *note record: XREFrecord.

 -- : soundsc (Y)
 -- : soundsc (Y, FS)
 -- : soundsc (Y, FS, NBITS)
 -- : soundsc (..., [YMIN, YMAX])
     Scale the audio data Y and play it at sample rate FS to the default
     audio device.

     The audio signal Y can be a vector or a two-column array,
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     By default, Y is automatically normalized to the range [-1, 1].  If
     the range [YMIN, YMAX] is given, then elements of Y that fall
     within the range YMIN ≤ Y ≤ YMAX are scaled to the range [-1, 1]
     instead.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note sound: XREFsound, *note record: XREFrecord.


File: octave.info,  Node: Object Oriented Programming,  Next: GUI Development,  Prev: Audio Processing,  Up: Top

34 Object Oriented Programming
******************************

Octave has the ability to create user-defined classes—including the
capabilities of operator and function overloading.  Classes can protect
internal properties so that they may not be altered accidentally which
facilitates data encapsulation.  In addition, rules can be created to
address the issue of class precedence in mixed class operations.

   This chapter discusses the means of constructing a user class, how to
query and set the properties of a class, and how to overload operators
and functions.  Throughout this chapter real code examples are given
using a class designed for polynomials.

* Menu:

* Creating a Class::
* Class Methods::
* Indexing Objects::
* Overloading Objects::
* Inheritance and Aggregation::
* classdef Classes::


File: octave.info,  Node: Creating a Class,  Next: Class Methods,  Up: Object Oriented Programming

34.1 Creating a Class
=====================

This chapter illustrates user-defined classes and object oriented
programming through a custom class designed for polynomials.  This class
was chosen for its simplicity which does not distract unnecessarily from
the discussion of the programming features of Octave.  Even so, a bit of
background on the goals of the polynomial class is necessary before the
syntax and techniques of Octave object oriented programming are
introduced.

   The polynomial class is used to represent polynomials of the form

     a0 + a1 * x + a2 * x^2 + ... + an * x^n

where a0, a1, etc. are real scalars.  Thus the polynomial can be
represented by a vector

     a = [a0, a1, a2, ..., an];

   This is a sufficient specification to begin writing the constructor
for the polynomial class.  All object oriented classes in Octave must be
located in a directory that is the name of the class prepended with the
‘@’ symbol.  For example, the polynomial class will have all of its
methods defined in the ‘@polynomial’ directory.

   The constructor for the class must be the name of the class itself;
in this example the constructor resides in the file
‘@polynomial/polynomial.m’.  Ideally, even when the constructor is
called with no arguments it should return a valid object.  A constructor
for the polynomial class might look like

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn
     
     function p = polynomial (a)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p.poly = 0;
         p = class (p, "polynomial");
       else
         if (isa (a, "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
     endfunction

   Note that the return value of the constructor must be the output of
the ‘class’ function.  The first argument to the ‘class’ function is a
structure and the second is the name of the class itself.  An example of
calling the class constructor to create an instance is

     p = polynomial ([1, 0, 1]);

   Methods are defined by m-files in the class directory and can have
embedded documentation the same as any other m-file.  The help for the
constructor can be obtained by using the constructor name alone, that
is, for the polynomial constructor ‘help polynomial’ will return the
help string.  Help can be restricted to a particular class by using the
class directory name followed by the method.  For example, ‘help
@polynomial/polynomial’ is another way of displaying the help string for
the polynomial constructor.  This second means is the only way to obtain
help for the overloaded methods and functions of a class.

   The same specification mechanism can be used wherever Octave expects
a function name.  For example ‘type @polynomial/disp’ will print the
code of the ‘disp’ method of the polynomial class to the screen, and
‘dbstop @polynomial/disp’ will set a breakpoint at the first executable
line of the ‘disp’ method of the polynomial class.

   To check whether a variable belongs to a user class, the ‘isobject’
and ‘isa’ functions can be used.  For example:

     p = polynomial ([1, 0, 1]);
     isobject (p)
       ⇒ 1
     isa (p, "polynomial")
       ⇒ 1

 -- : isobject (X)
     Return true if X is a class object.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo,
     *note isa: XREFisa, *note ismethod: XREFismethod, *note isprop:
     XREFisprop.

The available methods of a class can be displayed with the ‘methods’
function.

 -- : methods (OBJ)
 -- : methods ("CLASSNAME")
 -- : methods (..., "-full")
 -- : MTDS = methods (...)
     List the names of the public methods for the object OBJ or the
     named class CLASSNAME.

     OBJ may be an Octave class object or a Java object.  CLASSNAME may
     be the name of an Octave class or a Java class.

     If the optional argument "-full" is given then Octave returns full
     method signatures which include output type, name of method, and
     the number and type of inputs.

     When called with no output arguments, ‘methods’ prints the list of
     method names to the screen.  Otherwise, the output argument MTDS
     contains the list in a cell array of strings.

     See also: *note ismethod: XREFismethod, *note properties:
     XREFproperties, *note fieldnames: XREFfieldnames.

To inquire whether a particular method exists for a user class, the
‘ismethod’ function can be used.

 -- : ismethod (OBJ, METHOD)
 -- : ismethod (CLASS_NAME, METHOD)
     Return true if the string METHOD is a valid method of the object
     OBJ or of the class CLSNAME.

     See also: *note isprop: XREFisprop, *note isobject: XREFisobject,
     *note isjava: XREFisjava, *note methods: XREFmethods.

For a polynomial class it makes sense to have a method to compute its
roots.

     function r = roots (p)
       r = roots (fliplr (p.poly));
     endfunction

   We can check for the existence of the ‘roots’-method by calling:

     p = polynomial ([1, 0, 1]);
     ismethod (p, "roots")
       ⇒ 1


File: octave.info,  Node: Class Methods,  Next: Indexing Objects,  Prev: Creating a Class,  Up: Object Oriented Programming

34.2 Class Methods
==================

There are a number of basic class methods that can (and should) be
defined to allow the contents of the classes to be queried and set.  The
most basic of these is the ‘disp’ method.  The ‘disp’ method is used by
Octave whenever a class should be displayed on the screen.  Usually this
is the result of an Octave expression that doesn’t end with a semicolon.
If this method is not defined, then Octave won’t print anything when
displaying the contents of a class which can be confusing.

An example of a ‘disp’ method for the polynomial class might be

     function disp (p)
     
       a = p.poly;
       first = true;
       for i = 1 : length (a);
         if (a(i) != 0)
           if (first)
             first = false;
           elseif (a(i) > 0 || isnan (a(i)))
             printf (" +");
           endif
           if (a(i) < 0)
             printf (" -");
           endif
           if (i == 1)
             printf (" %.5g", abs (a(i)));
           elseif (abs (a(i)) != 1)
             printf (" %.5g *", abs (a(i)));
           endif
           if (i > 1)
             printf (" X");
           endif
           if (i > 2)
             printf (" ^ %d", i - 1);
           endif
         endif
       endfor
     
       if (first)
         printf (" 0");
       endif
       printf ("\n");
     
     endfunction

   To be consistent with the Octave graphic handle classes, a class
should also define the ‘get’ and ‘set’ methods.  The ‘get’ method
accepts one or two arguments.  The first argument is an object of the
appropriate class.  If no second argument is given then the method
should return a structure with all the properties of the class.  If the
optional second argument is given it should be a property name and the
specified property should be retrieved.

     function val = get (p, prop)
     
       if (nargin < 1 || nargin > 2)
         print_usage ();
       endif
     
       if (nargin == 1)
         val.poly = p.poly;
       else
         if (! ischar (prop))
           error ("@polynomial/get: PROPERTY must be a string");
         endif
     
         switch (prop)
           case "poly"
             val = p.poly;
           otherwise
             error ('@polynomial/get: invalid PROPERTY "%s"', prop);
         endswitch
       endif
     
     endfunction

Similarly, the first argument to the ‘set’ method should be an object
and any additional arguments should be property/value pairs.

     function pout = set (p, varargin)
     
       if (numel (varargin) < 2 || rem (numel (varargin), 2) != 0)
         error ("@polynomial/set: expecting PROPERTY/VALUE pairs");
       endif
     
       pout = p;
       while (numel (varargin) > 1)
         prop = varargin{1};
         val  = varargin{2};
         varargin(1:2) = [];
         if (! ischar (prop) || ! strcmp (prop, "poly"))
           error ("@polynomial/set: invalid PROPERTY for polynomial class");
         elseif (! (isreal (val) && isvector (val)))
           error ("@polynomial/set: VALUE must be a real vector");
         endif
     
         pout.poly = val(:).';  # force row vector
       endwhile
     
     endfunction

Note that Octave does not implement pass by reference; Therefore, to
modify an object requires an assignment statement using the return value
from the ‘set’ method.

     p = set (p, "poly", [1, 0, 0, 0, 1]);

The ‘set’ method makes use of the ‘subsasgn’ method of the class, and
therefore this method must also be defined.  The ‘subsasgn’ method is
discussed more thoroughly in the next section (*note Indexing
Objects::).

   Finally, user classes can be considered to be a special type of a
structure, and they can be saved to a file in the same manner as a
structure.  For example:

     p = polynomial ([1, 0, 1]);
     save userclass.mat p
     clear p
     load userclass.mat

All of the file formats supported by ‘save’ and ‘load’ are supported.
In certain circumstances a user class might contain a field that it
doesn’t make sense to save, or a field that needs to be initialized
before it is saved.  This can be done with the ‘saveobj’ method of the
class.

 -- : B = saveobj (A)
     Method of a class to manipulate an object prior to saving it to a
     file.

     The function ‘saveobj’ is called when the object A is saved using
     the ‘save’ function.  An example of the use of ‘saveobj’ might be
     to remove fields of the object that don’t make sense to be saved or
     it might be used to ensure that certain fields of the object are
     initialized before the object is saved.  For example:

          function b = saveobj (a)
            b = a;
            if (isempty (b.field))
               b.field = initfield (b);
            endif
          endfunction

     See also: *note loadobj: XREFloadobj, *note class: XREFclass.

‘saveobj’ is called just prior to saving the class to a file.
Similarly, the ‘loadobj’ method is called just after a class is loaded
from a file, and can be used to ensure that any removed fields are
reinserted into the user object.

 -- : B = loadobj (A)
     Method of a class to manipulate an object after loading it from a
     file.

     The function ‘loadobj’ is called when the object A is loaded using
     the ‘load’ function.  An example of the use of ‘saveobj’ might be
     to add fields to an object that don’t make sense to be saved.  For
     example:

          function b = loadobj (a)
            b = a;
            b.addmissingfield = addfield (b);
          endfunction

     See also: *note saveobj: XREFsaveobj, *note class: XREFclass.


File: octave.info,  Node: Indexing Objects,  Next: Overloading Objects,  Prev: Class Methods,  Up: Object Oriented Programming

34.3 Indexing Objects
=====================

* Menu:

* Defining Indexing And Indexed Assignment::
* Indexed Assignment Optimization::


File: octave.info,  Node: Defining Indexing And Indexed Assignment,  Next: Indexed Assignment Optimization,  Up: Indexing Objects

34.3.1 Defining Indexing And Indexed Assignment
-----------------------------------------------

Objects can be indexed with parentheses or braces, either like
‘OBJ(IDX)’ or like ‘OBJ{IDX}’, or even like ‘OBJ(IDX).FIELD’.  However,
it is up to the programmer to decide what this indexing actually means.
In the case of the polynomial class ‘P(N)’ might mean either the
coefficient of the N-th power of the polynomial, or it might be the
evaluation of the polynomial at N.  The meaning of this subscripted
referencing is determined by the ‘subsref’ method.

 -- : subsref (VAL, IDX)
     Perform the subscripted element selection operation on VAL
     according to the subscript specified by IDX.

     The subscript IDX must be a structure array with fields ‘type’ and
     ‘subs’.  Valid values for ‘type’ are "()", "{}", and ".".  The
     ‘subs’ field may be either ":" or a cell array of index values.

     The following example shows how to extract the first two columns of
     a matrix

          val = magic (3)
              ⇒ val = [ 8   1   6
                         3   5   7
                         4   9   2 ]
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsref (val, idx)
               ⇒ [ 8   1
                    3   5
                    4   9 ]

     Note that this is the same as writing ‘val(:, 1:2)’.

     If IDX is an empty structure array with fields ‘type’ and ‘subs’,
     return VAL.

     See also: *note subsasgn: XREFsubsasgn, *note substruct:
     XREFsubstruct.

   For example, this class uses the convention that indexing with "()"
evaluates the polynomial and indexing with "{}" returns the N-th
coefficient (of the N-th power).  The code for the ‘subsref’ method
looks like

     function r = subsref (p, s)
     
       if (isempty (s))
         error ("@polynomial/subsref: missing index");
       endif
     
       switch (s(1).type)
     
         case "()"
           idx = s(1).subs;
           if (numel (idx) != 1)
             error ("@polynomial/subsref: need exactly one index");
           endif
           r = polyval (fliplr (p.poly), idx{1});
     
         case "{}"
           idx = s(1).subs;
           if (numel (idx) != 1)
             error ("@polynomial/subsref: need exactly one index");
           endif
     
           if (isnumeric (idx{1}))
             r = p.poly(idx{1}+1);
           else
             r = p.poly(idx{1});
           endif
     
         case "."
           fld = s.subs;
           if (! strcmp (fld, "poly"))
             error ('@polynomial/subsref: invalid property "%s"', fld);
           endif
           r = p.poly;
     
         otherwise
           error ("@polynomial/subsref: invalid subscript type");
     
       endswitch
     
       if (numel (s) > 1)
         r = subsref (r, s(2:end));
       endif
     
     endfunction

   The equivalent functionality for subscripted assignments uses the
‘subsasgn’ method.

 -- : subsasgn (VAL, IDX, RHS)
     Perform the subscripted assignment operation according to the
     subscript specified by IDX.

     The subscript IDX must be a structure array with fields ‘type’ and
     ‘subs’.  Valid values for ‘type’ are "()", "{}", and ".".  The
     ‘subs’ field may be either ":" or a cell array of index values.

     The following example shows how to set the two first columns of a
     3-by-3 matrix to zero.

          val = magic (3);
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsasgn (val, idx, 0)
               ⇒  [ 0   0   6
                     0   0   7
                     0   0   2 ]

     Note that this is the same as writing ‘val(:, 1:2) = 0’.

     If IDX is an empty structure array with fields ‘type’ and ‘subs’,
     return RHS.

     See also: *note subsref: XREFsubsref, *note substruct:
     XREFsubstruct, *note optimize_subsasgn_calls:
     XREFoptimize_subsasgn_calls.

 -- : VAL = optimize_subsasgn_calls ()
 -- : OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- : optimize_subsasgn_calls (NEW_VAL, "local")
     Query or set the internal flag for ‘subsasgn’ method call
     optimizations.

     If true, Octave will attempt to eliminate the redundant copying
     when calling the ‘subsasgn’ method of a user-defined class.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     See also: *note subsasgn: XREFsubsasgn.

   Note that the ‘subsref’ and ‘subsasgn’ methods always receive the
whole index chain, while they usually handle only the first element.  It
is the responsibility of these methods to handle the rest of the chain
(if needed), usually by forwarding it again to ‘subsref’ or ‘subsasgn’.

   If you wish to use the ‘end’ keyword in subscripted expressions of an
object, then there must be an ‘end’ method defined.  For example, the
‘end’ method for the polynomial class might look like

     function r = end (obj, index_pos, num_indices)
     
       if (num_indices != 1)
         error ("polynomial object may only have one index");
       endif
     
       r = length (obj.poly) - 1;
     
     endfunction

which is a fairly generic ‘end’ method that has a behavior similar to
the ‘end’ keyword for Octave Array classes.  An example using the
polynomial class is then

     p = polynomial ([1,2,3,4]);
     p{end-1}
       ⇒ 3

   Objects can also be used themselves as the index in a subscripted
expression and this is controlled by the ‘subsindex’ function.

 -- : IDX = subsindex (OBJ)
     Convert an object to an index vector.

     When OBJ is a class object defined with a class constructor, then
     ‘subsindex’ is the overloading method that allows the conversion of
     this class object to a valid indexing vector.  It is important to
     note that ‘subsindex’ must return a zero-based real integer vector
     of the class "double".  For example, if the class constructor were

          function obj = myclass (a)
            obj = class (struct ("a", a), "myclass");
          endfunction

     then the ‘subsindex’ function

          function idx = subsindex (obj)
            idx = double (obj.a) - 1.0;
          endfunction

     could be used as follows

          a = myclass (1:4);
          b = 1:10;
          b(a)
          ⇒ 1  2  3  4

     See also: *note class: XREFclass, *note subsref: XREFsubsref, *note
     subsasgn: XREFsubsasgn.

   Finally, objects can be used like ranges by providing a ‘colon’
method.

 -- : R = colon (BASE, LIMIT)
 -- : R = colon (BASE, INCREMENT, LIMIT)
     Return the result of the colon expression corresponding to BASE,
     LIMIT, and optionally, INCREMENT.

     This function is equivalent to the operator syntax ‘BASE : LIMIT’
     or ‘BASE : INCREMENT : LIMIT’.

     See also: *note linspace: XREFlinspace.


File: octave.info,  Node: Indexed Assignment Optimization,  Prev: Defining Indexing And Indexed Assignment,  Up: Indexing Objects

34.3.2 Indexed Assignment Optimization
--------------------------------------

Octave’s ubiquitous lazily-copied pass-by-value semantics implies a
problem for performance of user-defined ‘subsasgn’ methods.  Imagine the
following call to ‘subsasgn’

     ss = substruct ("()", {1});
     x = subsasgn (x, ss, 1);

where the corresponding method looking like this:

     function x = subsasgn (x, ss, val)
       ...
       x.myfield (ss.subs{1}) = val;
     endfunction

   The problem is that on entry to the ‘subsasgn’ method, ‘x’ is still
referenced from the caller’s scope, which means that the method will
first need to unshare (copy) ‘x’ and ‘x.myfield’ before performing the
assignment.  Upon completing the call, unless an error occurs, the
result is immediately assigned to ‘x’ in the caller’s scope, so that the
previous value of ‘x.myfield’ is forgotten.  Hence, the Octave language
implies a copy of N elements (N being the size of ‘x.myfield’), where
modifying just a single element would actually suffice.  In other words,
a constant-time operation is degraded to linear-time one.  This may be a
real problem for user classes that intrinsically store large arrays.

   To partially solve the problem Octave uses a special optimization for
user-defined ‘subsasgn’ methods coded as m-files.  When the method gets
called as a result of the built-in assignment syntax (not a direct
‘subsasgn’ call as shown above), i.e., ‘x(1) = 1’, AND if the ‘subsasgn’
method is declared with identical input and output arguments, as in the
example above, then Octave will ignore the copy of ‘x’ inside the
caller’s scope; therefore, any changes made to ‘x’ during the method
execution will directly affect the caller’s copy as well.  This allows,
for instance, defining a polynomial class where modifying a single
element takes constant time.

   It is important to understand the implications that this optimization
brings.  Since no extra copy of ‘x’ will exist in the caller’s scope, it
is _solely_ the callee’s responsibility to not leave ‘x’ in an invalid
state if an error occurs during the execution.  Also, if the method
partially changes ‘x’ and then errors out, the changes _will_ affect ‘x’
in the caller’s scope.  Deleting or completely replacing ‘x’ inside
subsasgn will not do anything, however, only indexed assignments matter.

   Since this optimization may change the way code works (especially if
badly written), a function ‘optimize_subsasgn_calls’ is provided to
control it.  This feature is enabled by default.  Another way to avoid
the optimization is to declare subsasgn methods with different output
and input arguments like this:

     function y = subsasgn (x, ss, val)
       ...
     endfunction


File: octave.info,  Node: Overloading Objects,  Next: Inheritance and Aggregation,  Prev: Indexing Objects,  Up: Object Oriented Programming

34.4 Overloading Objects
========================

* Menu:

* Function Overloading::
* Operator Overloading::
* Precedence of Objects::


File: octave.info,  Node: Function Overloading,  Next: Operator Overloading,  Up: Overloading Objects

34.4.1 Function Overloading
---------------------------

Any Octave function can be overloaded, and this allows an
object-specific version of a function to be called as needed.  A
pertinent example for the polynomial class might be to overload the
‘polyval’ function.

     function [y, dy] = polyval (p, varargin)
     
       if (nargout > 1)
         [y, dy] = polyval (fliplr (p.poly), varargin{:});
       else
         y = polyval (fliplr (p.poly), varargin{:});
       endif
     
     endfunction

   This function just hands off the work to the normal Octave ‘polyval’
function.  Another interesting example of an overloaded function for the
polynomial class is the ‘plot’ function.

     function h = plot (p, varargin)
     
       n = 128;
       rmax = max (abs (roots (p.poly)));
       x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
       if (nargout > 0)
         h = plot (x, polyval (p, x), varargin{:});
       else
         plot (x, polyval (p, x), varargin{:});
       endif
     
     endfunction

which allows polynomials to be plotted in the domain near the region of
the roots of the polynomial.

   Functions that are of particular interest for overloading are the
class conversion functions such as ‘double’.  Overloading these
functions allows the ‘cast’ function to work with a user class.  It can
also aid in the use of a class object with methods and functions from
other classes since the object can be transformed to the requisite input
form for the new function.  An example ‘double’ function for the
polynomial class might look like

     function a = double (p)
       a = p.poly;
     endfunction


File: octave.info,  Node: Operator Overloading,  Next: Precedence of Objects,  Prev: Function Overloading,  Up: Overloading Objects

34.4.2 Operator Overloading
---------------------------

The following table shows, for each built-in numerical operation, the
corresponding function name to use when providing an overloaded method
for a user class.

Operation              Method                 Description
----------------------------------------------------------------------------
‘a + b’                ‘plus (a, b)’          Binary addition
‘a - b’                ‘minus (a, b)’         Binary subtraction
‘+a’                   ‘uplus (a)’            Unary addition
‘-a’                   ‘uminus (a)’           Unary subtraction
‘a .* b’               ‘times (a, b)’         Element-wise multiplication
‘a * b’                ‘mtimes (a, b)’        Matrix multiplication
‘a ./ b’               ‘rdivide (a, b)’       Element-wise right division
‘a / b’                ‘mrdivide (a, b)’      Matrix right division
‘a .\ b’               ‘ldivide (a, b)’       Element-wise left division
‘a \ b’                ‘mldivide (a, b)’      Matrix left division
‘a .^ b’               ‘power (a, b)’         Element-wise power
‘a ^ b’                ‘mpower (a, b)’        Matrix power
‘a < b’                ‘lt (a, b)’            Less than
‘a <= b’               ‘le (a, b)’            Less than or equal to
‘a > b’                ‘gt (a, b)’            Greater than
‘a >= b’               ‘ge (a, b)’            Greater than or equal to
‘a == b’               ‘eq (a, b)’            Equal to
‘a != b’               ‘ne (a, b)’            Not equal to
‘a & b’                ‘and (a, b)’           Logical and
‘a | b’                ‘or (a, b)’            Logical or
‘!a’                   ‘not (a)’              Logical not
‘a'’                   ‘ctranspose (a)’       Complex conjugate transpose
‘a.'’                  ‘transpose (a)’        Transpose
‘a:b’                  ‘colon (a, b)’         Two element range
‘a:b:c’                ‘colon (a, b, c)’      Three element range
‘[a, b]’               ‘horzcat (a, b)’       Horizontal concatenation
‘[a; b]’               ‘vertcat (a, b)’       Vertical concatenation
‘a(s_1,...,s_n)’       ‘subsref (a, s)’       Subscripted reference
‘a(s_1,...,s_n) = b’   ‘subsasgn (a, s, b)’   Subscripted assignment
‘b(a)’                 ‘subsindex (a)’        Convert object to index
‘disp’                 ‘disp (a)’             Object display

Table 34.1: Available overloaded operators and their corresponding class
method

   An example ‘mtimes’ method for the polynomial class might look like

     function p = mtimes (a, b)
       p = polynomial (conv (double (a), double (b)));
     endfunction


File: octave.info,  Node: Precedence of Objects,  Prev: Operator Overloading,  Up: Overloading Objects

34.4.3 Precedence of Objects
----------------------------

Many functions and operators take two or more arguments and the
situation can easily arise where these functions are called with objects
of different classes.  It is therefore necessary to determine the
precedence of which method from which class to call when there are mixed
objects given to a function or operator.  To do this the ‘superiorto’
and ‘inferiorto’ functions can be used

 -- : superiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a higher precedence than CLASS_NAME.

     More that one such class can be specified in a single call.  This
     function may _only_ be called from a class constructor.

     See also: *note inferiorto: XREFinferiorto.

 -- : inferiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a lower precedence than CLASS_NAME.

     More that one such class can be specified in a single call.  This
     function may _only_ be called from a class constructor.

     See also: *note superiorto: XREFsuperiorto.

   With the polynomial class, consider the case

     2 * polynomial ([1, 0, 1]);

that mixes an object of the class "double" with an object of the class
"polynomial".  In this case the return type should be "polynomial" and
so the ‘superiorto’ function is used in the class constructor.  In
particular the polynomial class constructor would be modified to

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn
     
     function p = polynomial (a)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       else
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
       superiorto ("double");
     
     endfunction

   Note that user classes _always_ have higher precedence than built-in
Octave types.  Thus, marking the polynomial class higher than the
"double" class is not actually necessary.

   When confronted with two objects of equal precedence, Octave will use
the method of the object that appears first in the list of arguments.


File: octave.info,  Node: Inheritance and Aggregation,  Next: classdef Classes,  Prev: Overloading Objects,  Up: Object Oriented Programming

34.5 Inheritance and Aggregation
================================

Using classes to build new classes is supported by Octave through the
use of both inheritance and aggregation.

   Class inheritance is provided by Octave using the ‘class’ function in
the class constructor.  As in the case of the polynomial class, the
Octave programmer will create a structure that contains the data fields
required by the class, and then call the ‘class’ function to indicate
that an object is to be created from the structure.  Creating a child of
an existing object is done by creating an object of the parent class and
providing that object as the third argument of the class function.

   This is most easily demonstrated by example.  Suppose the programmer
needs a FIR filter, i.e., a filter with a numerator polynomial but a
denominator of 1.  In traditional Octave programming this would be
performed as follows.

     >> x = [some data vector];
     >> n = [some coefficient vector];
     >> y = filter (n, 1, x);

   The equivalent behavior can be implemented as a class ‘@FIRfilter’.
The constructor for this class is the file ‘FIRfilter.m’ in the class
directory ‘@FIRfilter’.

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (! isa (p, "polynomial"))
         error ("@FIRfilter: P must be a polynomial object");
       endif
     
       f.polynomial = [];
       f = class (f, "FIRfilter", p);
     
     endfunction

   As before, the leading comments provide documentation for the class
constructor.  This constructor is very similar to the polynomial class
constructor, except that a polynomial object is passed as the third
argument to the ‘class’ function, telling Octave that the ‘FIRfilter’
class will be derived from the polynomial class.  The FIR filter class
itself does not have any data fields, but it must provide a struct to
the ‘class’ function.  Given that the ‘@polynomial’ constructor will add
an element named POLYNOMIAL to the object struct, the ‘@FIRfilter’ just
initializes a struct with a dummy field POLYNOMIAL which will later be
overwritten.

   Note that the sample code always provides for the case in which no
arguments are supplied.  This is important because Octave will call a
constructor with no arguments when loading objects from saved files in
order to determine the inheritance structure.

   A class may be a child of more than one class (*note class:
XREFclass.), and inheritance may be nested.  There is no limitation to
the number of parents or the level of nesting other than memory or other
physical issues.

   For the ‘FIRfilter’ class, more control about the object display is
desired.  Therefore, the ‘display’ method rather than the ‘disp’ method
is overloaded (*note Class Methods::).  A simple example might be

     function display (f)
       printf ("%s.polynomial", inputname (1));
       disp (f.polynomial);
     endfunction

   Note that the ‘FIRfilter’’s display method relies on the ‘disp’
method from the ‘polynomial’ class to actually display the filter
coefficients.  Furthermore, note that in the ‘display’ method it makes
sense to start the method with the line ‘printf ("%s =", inputname (1))’
to be consistent with the rest of Octave which prints the variable name
to be displayed followed by the value.  In general it is not recommended
to overload the ‘display’ function.

 -- : display (OBJ)
     Display the contents of the object OBJ prepended by its name.

     The Octave interpreter calls the ‘display’ function whenever it
     needs to present a class on-screen.  Typically, this would be a
     statement which does not end in a semicolon to suppress output.
     For example:

          myclass (...)

     Or:

          myobj = myclass (...)

     In general, user-defined classes should overload the ‘disp’ method
     to avoid the default output:

          myobj = myclass (...)
            ⇒ myobj =

            <class myclass>

     When overloading the ‘display’ method instead, one has to take care
     of properly displaying the object’s name.  This can be done by
     using the ‘inputname’ function.

     See also: *note disp: XREFdisp, *note class: XREFclass, *note
     subsref: XREFsubsref, *note subsasgn: XREFsubsasgn.

   Once a constructor and display method exist, it is possible to create
an instance of the class.  It is also possible to check the class type
and examine the underlying structure.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
     f.polynomial = 0.33333 + 0.33333 * X + 0.33333 * X ^ 2
     octave:2> class (f)
     ans = FIRfilter
     octave:3> isa (f, "FIRfilter")
     ans =  1
     octave:4> isa (f, "polynomial")
     ans =  1
     octave:5> struct (f)
     ans =

       scalar structure containing the fields:

     polynomial = 0.33333 + 0.33333 * X + 0.33333 * X ^ 2

   The only thing remaining to make this class usable is a method for
processing data.  But before that, it is usually desirable to also have
a way of changing the data stored in a class.  Since the fields in the
underlying struct are private by default, it is necessary to provide a
mechanism to access the fields.  The ‘subsref’ method may be used for
both tasks.

     function r = subsref (f, x)
     
       switch (x.type)
     
         case "()"
           n = f.polynomial;
           r = filter (n.poly, 1, x.subs{1});
     
         case "."
           fld = x.subs;
           if (! strcmp (fld, "polynomial"))
             error ('@FIRfilter/subsref: invalid property "%s"', fld);
           endif
           r = f.polynomial;
     
         otherwise
           error ("@FIRfilter/subsref: invalid subscript type for FIR filter");
     
       endswitch
     
     endfunction

   The "()" case allows us to filter data using the polynomial provided
to the constructor.

     octave:2> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:3> x = ones (5,1);
     octave:4> y = f(x)
     y =

        0.33333
        0.66667
        1.00000
        1.00000
        1.00000

   The "."  case allows us to view the contents of the polynomial field.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:2> f.polynomial
     ans = 0.33333 + 0.33333 * X + 0.33333 * X ^ 2

   In order to change the contents of the object a ‘subsasgn’ method is
needed.  For example, the following code makes the polynomial field
publicly writable

     function fout = subsasgn (f, index, val)
     
       switch (index.type)
         case "."
           fld = index.subs;
           if (! strcmp (fld, "polynomial"))
             error ('@FIRfilter/subsasgn: invalid property "%s"', fld);
           endif
           fout = f;
           fout.polynomial = val;
     
         otherwise
           error ("@FIRfilter/subsasgn: Invalid index type")
       endswitch
     
     endfunction

so that

     octave:1> f = FIRfilter ();
     octave:2> f.polynomial = polynomial ([1 2 3])
     f.polynomial = 1 + 2 * X + 3 * X ^ 2

   Defining the FIRfilter class as a child of the polynomial class
implies that a FIRfilter object may be used any place that a polynomial
object may be used.  This is not a normal use of a filter.  It may be a
more sensible design approach to use aggregation rather than
inheritance.  In this case, the polynomial is simply a field in the
class structure.  A class constructor for the aggregation case might be

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       else
         if (! isa (p, "polynomial"))
           error ("@FIRfilter: P must be a polynomial object");
         endif
     
         f.polynomial = p;
       endif
     
       f = class (f, "FIRfilter");
     
     endfunction

   For this example only the constructor needs changing, and all other
class methods stay the same.


File: octave.info,  Node: classdef Classes,  Prev: Inheritance and Aggregation,  Up: Object Oriented Programming

34.6 ‘classdef’ Classes
=======================

Since version 4.0, Octave has limited support for ‘classdef’ classes.
In contrast to the aforementioned classes, called “old style classes” in
this section, ‘classdef’ classes can be defined within a single m-file.
Other innovations of ‘classdef’ classes are:

   • access rights for properties and methods,

   • static methods, i.e., methods that are independent of an object,
     and

   • the distinction between value and handle classes.

   Several features have to be added in future versions of Octave to be
fully compatible to MATLAB.  An overview of what is missing can be found
at <https://wiki.octave.org/Classdef>.

* Menu:

* Creating a classdef Class::
* Properties::
* Methods::
* Inheritance::
* Value Classes vs. Handle Classes::


File: octave.info,  Node: Creating a classdef Class,  Next: Properties,  Up: classdef Classes

34.6.1 Creating a ‘classdef’ Class
----------------------------------

A very basic ‘classdef’ value class (*note Value Classes vs. Handle
Classes::) is defined by:

     classdef some_class
       properties
       endproperties

       methods
       endmethods
     endclassdef

   In contrast to old style classes, the ‘properties’-‘endproperties’
block as well as the ‘methods’-‘endmethods’ block can be used to define
properties and methods of the class.  Because both blocks are empty,
they can be omitted in this particular case.

   For simplicity, a more advanced implementation of a ‘classdef’ class
is shown using the ‘polynomial’ example again (*note Creating a
Class::):

     classdef polynomial2
       properties
         poly = 0;
       endproperties
     
       methods
         function p = polynomial2 (a)
           if (nargin > 1)
             print_usage ();
           endif
     
           if (nargin == 1)
             if (isa (a, "polynomial2"))
               p.poly = a.poly;
             elseif (isreal (a) && isvector (a))
               p.poly = a(:).';  # force row vector
             else
               error ("polynomial2: A must be a real vector");
             endif
           endif
         endfunction
     
         function disp (p)
           a = p.poly;
           first = true;
           for i = 1 : length (a);
             if (a(i) != 0)
               if (first)
                 first = false;
               elseif (a(i) > 0 || isnan (a(i)))
                 printf (" +");
               endif
               if (a(i) < 0)
                 printf (" -");
               endif
               if (i == 1)
                 printf (" %.5g", abs (a(i)));
               elseif (abs (a(i)) != 1)
                 printf (" %.5g *", abs (a(i)));
               endif
               if (i > 1)
                 printf (" X");
               endif
               if (i > 2)
                 printf (" ^ %d", i - 1);
               endif
             endif
           endfor
     
           if (first)
             printf (" 0");
           endif
           printf ("\n");
         endfunction
       endmethods
     endclassdef

An object of class ‘polynomial2’ is created by calling the class
constructor:

     >> p = polynomial2 ([1, 0, 1])
     ⇒ p =

      1 + X ^ 2


File: octave.info,  Node: Properties,  Next: Methods,  Prev: Creating a classdef Class,  Up: classdef Classes

34.6.2 Properties
-----------------

All class properties must be defined within ‘properties’ blocks.  The
definition of a default value for a property is optional and can be
omitted.  The default initial value for each class property is ‘[]’.

   A ‘properties’ block can have additional attributes to specify access
rights or to define constants:

     classdef some_class
       properties (Access = MODE)
         PROP1
       endproperties

       properties (SetAccess = MODE, GetAccess = MODE)
         PROP2
       endproperties

       properties (Constant = true)
         PROP3 = pi ()
       endproperties

       properties
         PROP4 = 1337
       endproperties
     endclassdef

where MODE can be one of:

‘public’
     The properties can be accessed from everywhere.

‘private’
     The properties can only be accessed from class methods.  Subclasses
     of that class cannot access them.

‘protected’
     The properties can only be accessed from class methods and from
     subclasses of that class.

   When creating an object of ‘some_class’, PROP1 has the default value
‘[]’ and reading from and writing to PROP1 is defined by a single MODE.
For PROP2 the read and write access can be set differently.  Finally,
PROP3 is a constant property which can only be initialized once within
the ‘properties’ block.

   By default, in the example PROP4, properties are not constant and
have public read and write access.

 -- : properties (CLASS_NAME)
 -- : properties (OBJ)
 -- : PLIST = properties (...)
     Return or display the public properties for the named class
     CLASS_NAME or classdef object OBJ.

     If an output value is requested, return the list of property names
     in a cell array.

     Programming Note: Property names are returned if the ‘GetAccess’
     attribute is public and if the ‘Hidden’ attribute is false.

     See also: *note methods: XREFmethods.


File: octave.info,  Node: Methods,  Next: Inheritance,  Prev: Properties,  Up: classdef Classes

34.6.3 Methods
--------------

All class methods must be defined within ‘methods’ blocks.  An exception
to this rule is described at the end of this subsection.  Those
‘methods’ blocks can have additional attributes specifying the access
rights or whether the methods are static, i.e., methods that can be
called without creating an object of that class.

     classdef some_class
       methods
         function obj = some_class ()
           disp ("New instance created.");
         endfunction

         function disp (obj)
           disp ("Here is some_class.");
         endfunction
       endmethods

       methods (Access = MODE)
         function r = func (obj, r)
           r = 2 * r;
         endfunction
       endmethods

       methods (Static = true)
         function c = circumference (radius)
           c = 2 * pi () .* radius;
         endfunction
       endmethods
     endclassdef

   The constructor of the class is declared in the ‘methods’ block and
must have the same name as the class and exactly one output argument
which is an object of its class.

   It is also possible to overload built-in or inherited methods, like
the ‘disp’ function in the example above to tell Octave how objects of
‘some_class’ should be displayed (*note Class Methods::).

   In general, the first argument in a method definition is always the
object that it is called from.  Class methods can either be called by
passing the object as the first argument to that method or by calling
the object followed by a dot ("‘.’") and the method’s name with
subsequent arguments:

     >> obj = some_class ();
     New instance created.
     >> disp (obj);   # both are
     >> obj.disp ();  # equal

   In ‘some_class’, the method ‘func’ is defined within a ‘methods’
block setting the ‘Access’ attribute to MODE, which is one of:

‘public’
     The methods can be accessed from everywhere.

‘private’
     The methods can only be accessed from other class methods.
     Subclasses of that class cannot access them.

‘protected’
     The methods can only be accessed from other class methods and from
     subclasses of that class.

The default access for methods is ‘public’.

   Finally, the method ‘circumference’ is defined in a static ‘methods’
block and can be used without creating an object of ‘some_class’.  This
is useful for methods, that do not depend on any class properties.  The
class name and the name of the static method, separated by a dot
("‘.’"), call this static method.  In contrast to non-static methods,
the object is not passed as first argument even if called using an
object of ‘some_class’.

     >> some_class.circumference (3)
     ⇒ ans =  18.850
     >> obj = some_class ();
     New instance created.
     >> obj.circumference (3)
     ⇒ ans =  18.850

   Additionally, class methods can be defined as functions in a folder
of the same name as the class prepended with the ‘@’ symbol (*note
Creating a Class::).  The main ‘classdef’ file has to be stored in this
class folder as well.


File: octave.info,  Node: Inheritance,  Next: Value Classes vs. Handle Classes,  Prev: Methods,  Up: classdef Classes

34.6.4 Inheritance
------------------

Classes can inherit from other classes.  In this case all properties and
methods of the superclass are inherited to the subclass, considering
their access rights.  Use this syntax to inherit from ‘superclass’:

     classdef subclass < superclass
       ...
     endclassdef


File: octave.info,  Node: Value Classes vs. Handle Classes,  Prev: Inheritance,  Up: classdef Classes

34.6.5 Value Classes vs. Handle Classes
---------------------------------------

There are two intrinsically different types of ‘classdef’ classes, whose
major difference is the behavior regarding variable assignment.  The
first type are value classes:

     classdef value_class
       properties
         prop1
       endproperties

       methods
         function obj = set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

Assigning an object of that class to another variable essentially
creates a new object:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  1

   But that also means that you might have to assign the output of a
method that changes properties back to the object manually:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> a.set_prop1 (3);
     ⇒ ans =

     <object value_class>

     >> ans.prop1
     ⇒ ans =  3
     >> a.prop1
     ⇒ ans =  1

   The second type are handle classes.  Those classes have to be derived
from the abstract ‘handle’ class:

     classdef handle_class < handle
       properties
         prop1
       endproperties

       methods
         function set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

   In the following example, the variables ‘a’ and ‘b’ refer to the very
same object of class ‘handle_class’:

     >> a = handle_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  2

   Object properties that are modified by a method of an handle class
are changed persistently:

     >> a.set_prop1 (3);
     >> a.prop1
     ⇒ ans =  3


File: octave.info,  Node: GUI Development,  Next: System Utilities,  Prev: Object Oriented Programming,  Up: Top

35 GUI Development
******************

Octave is principally a batch or command-line language.  However, it
does offer some features for constructing graphical interfaces that
interact with users.

   The GUI elements available are I/O dialogs, a progress bar, and UI
elements for plot windows.  For example, rather than hardcoding a
filename for output results a script can open a dialog box and allow the
user to choose a file.  Similarly, if a calculation is expected to take
a long time a script can display a progress bar.  The various UI
elements can be used to fully customize the plot window with menubars,
toolbars, context menus, pushbuttons, sliders, etc.

   Several utility functions make it possible to store private data for
use with a GUI which will not pollute the user’s variable space.

   Finally, a program written in Octave might want to have long term
storage of preferences or state variables.  This can be done with
user-defined preferences.

* Menu:

* I/O Dialogs::
* Progress Bar::
* UI Elements::
* GUI Utility Functions::
* User-Defined Preferences::
* Octave Workspace Windows::


File: octave.info,  Node: I/O Dialogs,  Next: Progress Bar,  Up: GUI Development

35.1 I/O Dialogs
================

Simple dialog menus are available for choosing directories or files.
They return a string variable which can then be used with any command
requiring a filename.

 -- : DIRNAME = uigetdir ()
 -- : DIRNAME = uigetdir (INIT_PATH)
 -- : DIRNAME = uigetdir (INIT_PATH, DIALOG_NAME)
     Open a GUI dialog for selecting a directory.

     If INIT_PATH is not given the current working directory is used.

     DIALOG_NAME may be used to customize the dialog title.

     The output DIRNAME is a character string with the name of the
     selected directory.  However, if the ‘Cancel’ button is clicked the
     output is of type double with the value ‘0’.

     See also: *note uigetfile: XREFuigetfile, *note uiputfile:
     XREFuiputfile.

 -- : [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- : [...] = uigetfile (FLT)
 -- : [...] = uigetfile (FLT, DIALOG_NAME)
 -- : [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- : [...] = uigetfile (..., "Position", [PX PY])
 -- : [...] = uigetfile (..., "MultiSelect", MODE)

     Open a GUI dialog for selecting a file and return the filename
     FNAME, the path to this file FPATH, and the filter index FLTIDX.

     FLT contains a (list of) file filter string(s) in one of the
     following formats:

     "/path/to/filename.ext"
          If a filename is given then the file extension is extracted
          and used as filter.  In addition, the path is selected as
          current path in the dialog and the filename is selected as
          default file.  Example: ‘uigetfile ("myfun.m")’

     A single file extension "*.ext"
          Example: ‘uigetfile ("*.ext")’

     A 2-column cell array
          containing a file extension in the first column and a brief
          description in the second column.  Example: ‘uigetfile
          ({"*.ext", "My Description";"*.xyz", "XYZ-Format"})’

          The filter string can also contain a semicolon separated list
          of filter extensions.  Example: ‘uigetfile
          ({"*.gif;*.png;*.jpg", "Supported Picture Formats"})’

     A directory name or path name
          If the folder name of path name contains a trailing file
          separator, the contents of that folder will be displayed.  If
          no trailing file separator is present the parent directory is
          listed.  The substring to the right of the rightmost file
          separator (if any) will be interpreted as a file or directory
          name and if that file or directory exists it will be
          highlighted.  If the path name or directory name is entirely
          or partly nonexistent, the current working directory will be
          displayed.  No filter will be active.

     DIALOG_NAME can be used to customize the dialog title.

     If DEFAULT_FILE is given then it will be selected in the GUI
     dialog.  If, in addition, a path is given it is also used as
     current path.

     The screen position of the GUI dialog can be set using the
     "Position" key and a 2-element vector containing the pixel
     coordinates.  Two or more files can be selected when setting the
     "MultiSelect" key to "on".  In that case FNAME is a cell array
     containing the files.

     The outputs FNAME and FPATH are strings returning the chosen name
     and path, respectively.  However, if the ‘Cancel’ button is clicked
     the outputs are of type double with a value of ‘0’.  FLTIDX is the
     index in the list of filter extensions FLT that was selected.

     See also: *note uiputfile: XREFuiputfile, *note uigetdir:
     XREFuigetdir.

 -- : [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME,
          DEFAULT_FILE)
     Open a GUI dialog for selecting a file.

     FLT contains a (list of) file filter string(s) in one of the
     following formats:

     "/path/to/filename.ext"
          If a filename is given the file extension is extracted and
          used as filter.  In addition the path is selected as current
          path in the dialog and the filename is selected as default
          file.  Example: ‘uiputfile ("myfun.m")’

     "*.ext"
          A single file extension.  Example: ‘uiputfile ("*.ext")’

     ‘{"*.ext", "My Description"}’
          A 2-column cell array containing the file extension in the 1st
          column and a brief description in the 2nd column.  Example:
          ‘uiputfile ({"*.ext","My Description";"*.xyz", "XYZ-Format"})’

     The filter string can also contain a semicolon separated list of
     filter extensions.  Example: ‘uiputfile ({"*.gif;*.png;*.jpg",
     "Supported Picture Formats"})’

     DIALOG_NAME can be used to customize the dialog title.  If
     DEFAULT_FILE is given it is preselected in the GUI dialog.  If, in
     addition, a path is given it is also used as current path.

     FNAME and FPATH return the chosen name and path, respectively.
     FLTIDX is the index in the list of filter extensions FLT that was
     selected.

     See also: *note uigetfile: XREFuigetfile, *note uigetdir:
     XREFuigetdir.

   Additionally, there are dialog boxes for displaying help messages,
warnings, or errors, and for getting text input from the user.

 -- : errordlg ()
 -- : errordlg (MSG)
 -- : errordlg (MSG, TITLE)
 -- : errordlg (MSG, TITLE, OPT)
 -- : H = errordlg (...)
     Display an error dialog box with error message MSG and caption
     TITLE.

     The default error message is "This is the default error string."
     and the default caption is "Error Dialog".

     The error message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The third optional argument OPT controls the behavior of the
     dialog.  See ‘msgbox’ for details.

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          errordlg ("Some fancy error occurred.");
          errordlg ("Some fancy error\nwith two lines.");
          errordlg ({"Some fancy error", "with two lines."});
          errordlg ("Some fancy error occurred.", "Fancy caption");

     See also: *note helpdlg: XREFhelpdlg, *note warndlg: XREFwarndlg,
     *note msgbox: XREFmsgbox, *note inputdlg: XREFinputdlg, *note
     listdlg: XREFlistdlg, *note questdlg: XREFquestdlg.

 -- : helpdlg ()
 -- : helpdlg (MSG)
 -- : helpdlg (MSG, TITLE)
 -- : H = helpdlg (...)
     Display a help dialog box with help message MSG and caption TITLE.

     The default help message is "This is the default help string." and
     the default caption is "Help Dialog".

     The help message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          helpdlg ("Some helpful text for the user.");
          helpdlg ("Some helpful text\nwith two lines.");
          helpdlg ({"Some helpful text", "with two lines."});
          helpdlg ("Some helpful text for the user.", "Fancy caption");

     See also: *note errordlg: XREFerrordlg, *note warndlg: XREFwarndlg,
     *note msgbox: XREFmsgbox, *note inputdlg: XREFinputdlg, *note
     listdlg: XREFlistdlg, *note questdlg: XREFquestdlg.

 -- : CSTR = inputdlg (PROMPT)
 -- : CSTR = inputdlg (PROMPT, TITLE)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS, OPTIONS)
     Return user input from a multi-textfield dialog box in a cell array
     of strings, or an empty cell array if the dialog is closed by the
     Cancel button.

     Inputs:

     PROMPT
          A cell array with strings labeling each text field.  This
          input is required.

     TITLE
          String to use for the caption of the dialog.  The default is
          "Input Dialog".

     ROWSCOLS
          Specifies the size of the text fields and can take three
          forms:

            1. a scalar value which defines the number of rows used for
               each text field.

            2. a vector which defines the individual number of rows used
               for each text field.

            3. a matrix which defines the individual number of rows and
               columns used for each text field.  In the matrix each row
               describes a single text field.  The first column
               specifies the number of input rows to use and the second
               column specifies the text field width.

     DEFAULTS
          A list of default values to place in each text field.  It must
          be a cell array of strings with the same size as PROMPT.

     OPTIONS
          Not supported, only for MATLAB compatibility.

     Example:

          prompt = {"Width", "Height", "Depth"};
          defaults = {"1.10", "2.20", "3.30"};
          rowscols = [1,10; 2,20; 3,30];
          dims = inputdlg (prompt, "Enter Box Dimensions", ...
                           rowscols, defaults);

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : [SEL, OK] = listdlg (KEY, VALUE, ...)
     Return user inputs from a list dialog box in a vector of selection
     indices (SEL) and a flag indicating how the user closed the dialog
     box (OK).

     The indices in SEL are 1-based.

     The value of OK is 1 if the user closed the box with the OK button,
     otherwise it is 0 and SEL is empty.

     Input arguments are specified in form of KEY, VALUE pairs.  The
     "ListString" argument pair *must* be specified.

     Valid KEY and VALUE pairs are:

     "ListString"
          a cell array of strings specifying the items to list in the
          dialog.

     "SelectionMode"
          can be either "Single" (only one item may be selected at a
          time) or "Multiple" (default).

     "ListSize"
          a two-element vector ‘[WIDTH, HEIGHT]’ specifying the size of
          the list field in pixels.  The default is [160, 300].

     "InitialValue"
          a vector containing 1-based indices of elements which will be
          pre-selected when the list dialog is first displayed.  The
          default is 1 (first item).

     "Name"
          a string to be used as the dialog caption.  Default is "".

     "PromptString"
          a cell array of strings to be displayed above the list of
          items.  Default is {}.

     "OKString"
          a string used to label the OK button.  Default is "OK".

     "CancelString"
          a string used to label the Cancel button.  Default is
          "Cancel".

     Example:

          my_options = {"An item", "another", "yet another"};
          [sel, ok] = listdlg ("ListString", my_options,
                               "SelectionMode", "Multiple");
          if (ok == 1)
            disp ("You selected:");
            for i = 1:numel (sel)
              disp (sprintf ("\t%s", my_options{sel(i)}));
            endfor
          else
            disp ("You cancelled.");
          endif

     See also: *note menu: XREFmenu, *note errordlg: XREFerrordlg, *note
     helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg, *note msgbox:
     XREFmsgbox, *note questdlg: XREFquestdlg, *note warndlg:
     XREFwarndlg.

 -- : H = msgbox (MSG)
 -- : H = msgbox (MSG, TITLE)
 -- : H = msgbox (MSG, TITLE, ICON)
 -- : H = msgbox (MSG, TITLE, "custom", CDATA)
 -- : H = msgbox (MSG, TITLE, "custom", CDATA, COLORMAP)
 -- : H = msgbox (..., OPT)
     Display MSG using a message dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional input TITLE (character string) can be used to decorate
     the dialog caption.

     The optional argument ICON selects a dialog icon.  It can be one of
     "none" (default), "error", "help", "warn", or "custom".  The latter
     must be followed by an image array CDATA, and for indexed images
     the associated colormap.

     The final optional argument OPT controls the behavior of the
     dialog.  If OPT is a string, it may be one of

     "non-modal" (default)
          The dialog is normal.

     "modal"
          If any dialogs already exist with the same title, the most
          recent is reused and all others are closed.  The dialog is
          displayed "modal" which means it prevents users from
          interacting with any other GUI element until the dialog has
          been closed.

     "replace"
          If any dialogs already exist with the same title, the most
          recent is reused and all others are closed.  The resulting
          dialog is set "non-modal".

     If OPT is a structure, it must contain fields "WindowStyle" and
     "Interpreter":

     "WindowStyle"
          The value must be "non-modal", "modal", or "replace".  See
          above.

     "Interpreter"
          Controls the "interpreter" property of the text object used
          for displaying the message.  The value must be "tex"
          (default), "none", or "latex".

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          msgbox ("Some message for the user.");
          msgbox ("Some message\nwith two lines.");
          msgbox ({"Some message", "with two lines."});
          msgbox ("Some message for the user.", "Fancy caption");

          ## A message dialog box with error icon
          msgbox ("Some message for the user.", "Fancy caption", "error");

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : BTN = questdlg (MSG)
 -- : BTN = questdlg (MSG, TITLE)
 -- : BTN = questdlg (MSG, TITLE, DEFAULT)
 -- : BTN = questdlg (MSG, TITLE, BTN1, BTN2, DEFAULT)
 -- : BTN = questdlg (MSG, TITLE, BTN1, BTN2, BTN3, DEFAULT)
     Display MSG using a question dialog box and return the caption of
     the activated button.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional TITLE (character string) can be used to specify the
     dialog caption.  It defaults to "Question Dialog".

     The dialog may contain two or three buttons which will all close
     the dialog.

     The string DEFAULT identifies the default button, which is
     activated by pressing the <ENTER> key.  It must match one of the
     strings given in BTN1, BTN2, or BTN3.

     If only MSG and TITLE are specified, three buttons with the default
     captions "Yes", "No", and "Cancel" are used.

     If only two button captions, BTN1 and BTN2, are specified the
     dialog will have only these two buttons.

     Examples:

          btn = questdlg ("Close Octave?", "Some fancy title", ...
                          "Yes", "No", "No");
          if (strcmp (btn, "Yes"))
            exit ();
          endif

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     msgbox: XREFmsgbox, *note warndlg: XREFwarndlg.

 -- : warndlg ()
 -- : warndlg (MSG)
 -- : warndlg (MSG, TITLE)
 -- : warndlg (MSG, TITLE, OPT)
 -- : H = warndlg (...)
     Display a warning dialog box with warning message MSG and caption
     TITLE.

     The default warning message is "This is the default warning
     string." and the default caption is "Warning Dialog".

     The warning message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The third optional argument OPT controls the behavior of the
     dialog.  See ‘msgbox’ for details.

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          warndlg ("Some warning text for the user.");
          warndlg ("Some warning text\nwith two lines.");
          warndlg ({"Some warning text", "with two lines."});
          warndlg ("Some warning text for the user.", "Fancy caption");

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note msgbox: XREFmsgbox, *note inputdlg: XREFinputdlg, *note
     listdlg: XREFlistdlg, *note questdlg: XREFquestdlg.

 -- : uisetfont ()
 -- : uisetfont (H)
 -- : uisetfont (FONTSTRUCT)
 -- : uisetfont (..., TITLE)
 -- : FONTSTRUCT = uisetfont (...)
     Open a font selection dialog.

     If the first argument is a handle to a text, axes, or uicontrol
     object, pressing the OK button will change the font properties of
     the object.

     The first argument may also be a structure with fields ‘FontName’,
     ‘FontWeight’, ‘FontAngle’, ‘FontUnits’, and ‘FontSize’, indicating
     the initially selected font.

     The title of the dialog window can be changed using the last
     argument TITLE.

     If an output argument FONTSTRUCT is requested, the selected font
     structure is returned.  Otherwise, the font information is
     displayed onscreen.

     See also: *note text: XREFtext, *note axes: XREFaxes, *note
     uicontrol: XREFuicontrol.

   For creating new dialog types, there is a dialog function.

 -- : H = dialog ()
 -- : H = dialog ("PROPERTY", VALUE, ...)

     Create an empty modal dialog window to which other uicontrols can
     be added.

     The dialog box is a figure object with properties as recommended
     for a dialog box.

     The default properties differing from a figure are:

     buttondownfcn
          ‘if isempty (allchild(gcbf)), close (gcbf), endif’

     colormap
          []

     color
          defaultuicontrolbackgroundcolor

     dockcontrols
          off

     handlevisibility
          callback

     integerhandle
          off

     inverthardcopy
          off

     menubar
          none

     numbertitle
          off

     paperpositionmode
          auto

     resize
          off

     windowstyle
          modal

     Multiple property-value pairs may be specified for the dialog
     object, but they must appear in pairs.

     The return value H is a graphics handle to the created figure.

     Example:

          ## create an empty dialog window titled "Dialog Example"
          h = dialog ("name", "Dialog Example");

          ## create a button (default style)
          b = uicontrol (h, "string", "OK",
                            "position", [10 10 150 40],
                            "callback", "delete (gcf)");

          ## wait for dialog to resume or close
          uiwait (h);

     See also: *note errordlg: XREFerrordlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg, *note
     figure: XREFfigure, *note uiwait: XREFuiwait.


File: octave.info,  Node: Progress Bar,  Next: UI Elements,  Prev: I/O Dialogs,  Up: GUI Development

35.2 Progress Bar
=================

 -- : H = waitbar (FRAC)
 -- : H = waitbar (FRAC, MSG)
 -- : H = waitbar (..., "createcancelbtn", FCN, ...)
 -- : H = waitbar (..., PROP, VAL, ...)
 -- : waitbar (FRAC)
 -- : waitbar (FRAC, H)
 -- : waitbar (FRAC, H, MSG)
     Return a handle H to a new progress indicator ("waitbar") object.

     The waitbar is filled to fraction FRAC which must be in the range
     [0, 1].

     The optional message MSG is centered and displayed above the
     waitbar.

     A cancel button can be added to the bottom of the waitbar using the
     "createcancelbtn" property of waitbar figures.  The action to be
     executed when the user presses the button is specified using a
     string or function handle FCN.

     The appearance of the waitbar figure window can be configured by
     passing PROP/VAL pairs to the function.

     When called with a single input the current waitbar, if it exists,
     is updated to the new value FRAC.  If there are multiple
     outstanding waitbars they can be updated individually by passing
     the handle H of the specific waitbar to modify.

     See also: *note delete: XREFdelete.


File: octave.info,  Node: UI Elements,  Next: GUI Utility Functions,  Prev: Progress Bar,  Up: GUI Development

35.3 UI Elements
================

The ui* series of functions work best with the ‘qt’ graphics toolkit,
although some functionality is available with the ‘fltk’ toolkit.  There
is no support for the ‘gnuplot’ toolkit.

 -- : uipanel (PROPERTY, VALUE, ...)
 -- : uipanel (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uipanel (...)

     Create a uipanel object.

     uipanels are used as containers to group other uicontrol objects.

     If PARENT is omitted then a uipanel for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uipanel relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uipanel object.

     The full list of properties is documented at *note Uipanel
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uipanel object.

     Examples:

          ## create figure and panel on it
          f = figure;
          p = uipanel ("title", "Panel Title", "position", [.25 .25 .5 .5]);

          ## add two buttons to the panel
          b1 = uicontrol ("parent", p, "string", "A Button", ...
                          "position", [18 10 150 36]);
          b2 = uicontrol ("parent", p, "string", "Another Button", ...
                          "position",[18 60 150 36]);


     See also: *note figure: XREFfigure, *note uicontrol: XREFuicontrol.

 -- : HUI = uibuttongroup (PROPERTY, VALUE, ...)
 -- : HUI = uibuttongroup (PARENT, PROPERTY, VALUE, ...)
 -- : uibuttongroup (H)

     Create a uibuttongroup object and return a handle to it.

     A uibuttongroup is used to group uicontrol objects.

     If PARENT is omitted then a uibuttongroup for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uibuttongroup relative to PARENT is
     created.

     Any provided property value pairs will override the default values
     of the created uibuttongroup object.

     The full list of properties is documented at *note Uibuttongroup
     Properties::.

     Examples:

          ## Create figure and panel on it
          f = figure;
          ## Create a button group
          gp = uibuttongroup (f, "Position", [ 0 0.5 1 1])
          ## Create a buttons in the group
          b1 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 1", ...
                          "Position", [ 10 150 100 50 ]);
          b2 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 2", ...
                          "Position", [ 10 50 100 30 ]);
          ## Create a button not in the group
          b3 = uicontrol (f, "style", "radiobutton", ...
                          "string", "Not in the group", ...
                          "Position", [ 10 50 100 50 ]);

     When called with a single argument H which is a handle to an
     existing uibuttongroup object, switch the focus to the specified
     uibuttongroup.  This functionality is not currently implemented.

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : HUI = uicontrol (PROPERTY, VALUE, ...)
 -- : HUI = uicontrol (PARENT, PROPERTY, VALUE, ...)
 -- : uicontrol (H)

     Create a uicontrol object and return a handle to it.

     A uicontrol object is used to create simple interactive controls
     such as push buttons, checkboxes, edit and list controls.

     If PARENT is omitted then a uicontrol for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uicontrol relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uicontrol object.

     The full list of properties is documented at *note Uicontrol
     Properties::.

     The type of uicontrol created is specified by the STYLE property.
     If no style property is provided, a push button will be created.

     Valid styles for uicontrol are:

     "checkbox"
          Create a checkbox control that allows user on/off selection.

     "edit"
          Create an edit control that allows user input of single or
          multiple lines of text.

     "listbox"
          Create a listbox control that displays a list of items and
          allows user selection of single or multiple items.

     "popupmenu"
          Create a popupmenu control that displays a list of options
          that can be selected when the user clicks on the control.

     "pushbutton"
          Create a push button control that allows user to press to
          cause an action.

     "radiobutton"
          Create a radio button control intended to be used for mutually
          exclusive input in a group of radiobutton controls.

     "slider"
          Create a slider control that allows user selection from a
          range of values by sliding knob on the control.

     "text"
          Create a static text control to display single or multiple
          lines of text.

     "togglebutton"
          Create a toggle button control that appears like a push button
          but allows the user to select between two states.

     Examples:

          ## Create figure and panel on it
          f = figure;
          ## Create a button (default style)
          b1 = uicontrol (f, "string", "A Button", ...
                             "position", [10 10 150 40]);
          ## Create an edit control
          e1 = uicontrol (f, "style", "edit", "string", "editable text", ...
                             "position", [10 60 300 40]);
          ## Create a checkbox
          c1 = uicontrol (f, "style", "checkbox", "string", "a checkbox", ...
                             "position", [10 120 150 40]);

     When called with a single argument H which is a handle to an
     existing uicontrol object, switch the keyboard focus to the
     specified uicontrol.  As a result, the uicontrol object will
     receive keyboard events that can be processed using the
     "keypressfcn" callback.

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : HUI = uitable (PROPERTY, VALUE, ...)
 -- : HUI = uitable (PARENT, PROPERTY, VALUE, ...)
     Create a uitable object and return a handle to it.

     A uitable object is used to show tables of data in a figure window.

     If PARENT is omitted then a uitable for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uitable relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uitable object.

     The full list of properties is documented at *note Uitable
     Properties::.

     Examples:

          ## Create figure and place a table on it
          f = figure ();
          m = magic (8);
          t = uitable (f, "Data", m, "ColumnWidth", { 40 });

          ## Create a table with labeled rows and columns
          f = figure ();
          d = reshape (1:9, [3, 3]);
          row_names = { "Row1", "Row2", "Row3" };
          col_names = { "Col1", "Col2", "Col3" };
          t = uitable (f, "Data", d, ...
                       "RowName", row_names, "ColumnName", col_names);

          p = get (t, "Position");
          e = get (t, "Extent");
          p(3:4) = e(3:4);
          set (t, "Position", p);

          ## Long demo with callbacks
          function uitable_demo ()
            f = figure ("Name", "uitable Demo", "Menu", "none", ...
                        "Position", [10 10 1000 680]);

            ## A basic example
            d = { "char"   , "A string";
                  "double" , 12.3456789;
                  "complex", 1+2i;
                  "bool"   , true;
                  "single" , single (12.3456789);
                  "int8"   , int8 (-128);
                  "uint8"  , uint8 (128);
                  "int16"  , int16 (-32768);
                  "uint16" , uint16 (32768);
                  "int32"  , int32 (-2147483648);
                  "uint32" , uint32 (2147483648);
                  "int64"  , int64 (-2147483649);
                  "uint64" , uint64 (2147843649)};

            popup_options = {"A", "B", "C", "D", "E"};

            columnformat_options = { "[]", "char", "pop-up", "numeric", ...
                                     "short", "short e", "short eng", ...
                                     "short g", "long", "long e", ...
                                     "long eng", "long g", "bank", "+", ...
                                     "rat", "logical"};
            columnformat_values = columnformat_options;
            columnformat_values{1} = "";
            columnformat_values{3} = popup_options;

            default_data = repmat (d(:,2), 1, columns (columnformat_options));
            b_add = uicontrol (f, "Position", [285 630 600 50], ...
                      "UserData", [rows(d), 1], ...
                      "Style", "pushbutton", ...
                      "String", "Set data at selected point to selected datatype");

            l_type_table = uicontrol (f, "Position", [ 0 603 120 25 ], ...
                "String", "Datatype Table:", ...
                "Style", "text");
            t_type_table = uitable (f, "Position", [ 0 530 1000 70 ], ...
                "Data", transpose (d(:, 2)), ...
                "ColumnName", transpose (d(:, 1)), ...
                "RowName", "Value", ...
                "CellSelectionCallback", ...
                     @(x, y) set (b_add, "UserData", y.Indices ));

            l_point_table = uicontrol (f, "Position", [ 0 640 60 25 ], ...
                "String", "Point:", ...
                "Style", "text");
            t_point_table = uitable (f, "Position", [ 80 630 160 42 ], ...
                "RowName", [], ...
                "ColumnName", {"x", "y"}, ...
                "Data", [ 1, 1 ], ...
                "ColumnEditable", true);

            l_editable_table = uicontrol (f, "Position", [ 0 502 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Columns Editable:");
            t_editable_table = ...
              uitable (f, "Position", [ 0 434 1000 65 ], ...
                          "Data", repmat (false, 1, columns (default_data)), ...
                          "ColumnEditable", true);

            l_format_table = uicontrol (f, "Position", [ 0 406 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Column Format:");
            t_format_table = ...
              uitable (f, "Position", [ 0 338 1000 65 ], ...
                          "Data", columnformat_options, ...
                          "ColumnEditable", true, ...
                          "ColumnFormat", arrayfun (@(x) {columnformat_options}, ...
                                                    1:columns (columnformat_options)));

            l_data_table = uicontrol (f, "Style", "text", ...
                                         "String", "Data:", ...
                                         "Position", [ 0 310 60 25 ]);
            t_data_table = uitable (f, "Position", [ 0 15 1000 290 ], ...
                "Data", default_data, ...
                "ColumnFormat", columnformat_values);

            set (t_format_table, ...
                 "CellEditCallback", ...
                 @(x, y) update_column_format (y.NewData, y.Indices, ...
                                                t_data_table, popup_options));
            set (t_point_table, "CellEditCallback", ...
                 @(x, y) validate_point_table (x, y, t_data_table));
            set (t_editable_table, "CellEditCallback", ...
                 @(x,y) set (t_data_table, ...
                              "ColumnEditable", get (t_editable_table, "Data")));
            set (b_add, ...
                 "Callback", @(x, y) update_data (b_add, t_point_table, ...
                                                   t_type_table, t_data_table));
            set (t_data_table, "CellSelectionCallback", ...
                 @(x, y) update_point_table (y.Indices, t_point_table));
          endfunction

          function validate_point_table (h, dat, t_data_table)
            if (! (dat.NewData > 0 && ...
              dat.NewData < size (get (t_data_table, "Data"), dat.Indices(1, 1)) + 1))

              d = get (h, "Data");
              d(dat.Indices) = 1;
              set (h, "Data", d);
            endif
          endfunction

          function update_column_format (format, indices, t_data_table, ...
                                         popup_options)
            cf = get (t_data_table, "ColumnFormat");
            if (strcmp (format, "[]"))
              format = "";
            elseif (strcmp (format, "pop-up"))
              format = popup_options;
            endif
            cf{indices(1,2)} = format;
            set (t_data_table, "ColumnFormat", cf);
          endfunction

          function update_point_table (indices, t_point_table)
            if (isempty (indices))
              indices = [1, 1];
            endif
            set (t_point_table, "Data", indices(1,:));
          endfunction

          function update_data (b_add, t_point_table, t_type_table, ...
                                t_data_table)
            indices = get (b_add, "UserData");
            if (isempty (indices))
              indices = [1, 1];
            endif
            d = get (t_data_table, "Data");
            t_type_table_data = get (t_type_table, "Data");
            p = get (t_point_table, "Data");
            d(p(1,2), p(1,1)) = t_type_table_data(indices(1,2));
            set (t_data_table, "Data", d);
          endfunction

     See also: *note figure: XREFfigure, *note uicontrol: XREFuicontrol.

 -- : HUI = uimenu (PROPERTY, VALUE, ...)
 -- : HUI = uimenu (H, PROPERTY, VALUE, ...)
     Create a uimenu object and return a handle to it.

     If H is omitted then a top-level menu for the current figure is
     created.  If H is given then a submenu relative to H is created.

     uimenu objects have the following specific properties:

     "accelerator"
          A string containing the key combination together with CTRL to
          execute this menu entry (e.g., "x" for CTRL+x).

     "callback"
          Is the function called when this menu entry is executed.  It
          can be either a function string (e.g., "myfun"), a function
          handle (e.g., @myfun) or a cell array containing the function
          handle and arguments for the callback function (e.g., {@myfun,
          arg1, arg2}).

     "checked"
          Can be set "on" or "off".  Sets a mark at this menu entry.

     "enable"
          Can be set "on" or "off".  If disabled the menu entry cannot
          be selected and it is grayed out.

     "foregroundcolor"
          A color value setting the text color for this menu entry.

     "label"
          A string containing the label for this menu entry.  A
          "&"-symbol can be used to mark the "accelerator" character
          (e.g., "E&xit")

     "position"
          An scalar value containing the relative menu position.  The
          entry with the lowest value is at the first position starting
          from left or top.

     "separator"
          Can be set "on" or "off".  If enabled it draws a separator
          line above the current position.  It is ignored for top level
          entries.

     The full list of properties is documented at *note Uimenu
     Properties::.

     Examples:

          f = uimenu ("label", "&File", "accelerator", "f");
          e = uimenu ("label", "&Edit", "accelerator", "e");
          uimenu (f, "label", "Close", "accelerator", "q", ...
                     "callback", "close (gcf)");
          uimenu (e, "label", "Toggle &Grid", "accelerator", "g", ...
                     "callback", "grid (gca)");

     See also: *note figure: XREFfigure.

 -- : HUI = uicontextmenu (PROPERTY, VALUE, ...)
 -- : HUI = uicontextmenu (H, PROPERTY, VALUE, ...)

     Create a uicontextmenu object and return a handle to it.

     If H is omitted then a uicontextmenu for the current figure is
     created.  If no figure is available, a new figure is created first.

     If H is given then a uicontextmenu relative to H is created.

     Any provided property value pairs will override the default values
     of the created uicontextmenu object.

     The full list of properties is documented at *note Uicontextmenu
     Properties::.

     Examples:

          ## create figure and uicontextmenu
          f = figure ();
          c = uicontextmenu (f);

          ## create menus in the context menu
          m1 = uimenu ("parent", c, "label", "Menu item 1", ...
                       "callback", "disp('menu item 1')");
          m2 = uimenu ("parent", c, "label", "Menu item 2", ...
                       "callback", "disp('menu item 2')");

          ## set the context menu for the figure
          set (f, "uicontextmenu", c);

     See also: *note figure: XREFfigure, *note uimenu: XREFuimenu.

 -- : uitoolbar (PROPERTY, VALUE, ...)
 -- : uitoolbar (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uitoolbar (...)

     Create a uitoolbar object.  A uitoolbar displays uitoggletool and
     uipushtool buttons.

     If PARENT is omitted then a uitoolbar for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uitoolbar relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uitoolbar object.

     The full list of properties is documented at *note Uitoolbar
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoolbar object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);

     See also: *note figure: XREFfigure, *note uitoggletool:
     XREFuitoggletool, *note uipushtool: XREFuipushtool.

 -- : uipushtool (PROPERTY, VALUE, ...)
 -- : uipushtool (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uipushtool (...)

     Create a uipushtool object.

     uipushtools are buttons that appear on a figure toolbar.  The
     button is created with a border that is shown when the user hovers
     over the button.  An image can be set using the cdata property.

     If PARENT is omitted then a uipushtool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uipushtool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uipushtool object.

     The full list of properties is documented at *note Uipushtool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uipushtool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add pushtool button to toolbar
          b = uipushtool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uitoggletool: XREFuitoggletool.

 -- : uitoggletool (PROPERTY, VALUE, ...)
 -- : uitoggletool (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uitoggletool (...)

     Create a uitoggletool object.

     uitoggletool are togglebuttons that appear on a figure toolbar.
     The button is created with a border that is shown when the user
     hovers over the button.  An image can be set using the cdata
     property.

     If PARENT is omitted then a uitoggletool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uitoggletool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uitoggletool object.

     The full list of properties is documented at *note Uitoggletool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoggletool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add uitoggletool button to toolbar
          b = uitoggletool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uipushtool: XREFuipushtool.

