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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007,
2011 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: Tests,  Next: Random Number Generation,  Prev: Distributions,  Up: Statistics

26.6 Tests
==========

Octave can perform many different statistical tests.  The following
table summarizes the available tests.

Hypothesis                    Test Functions
------------------------------------------------------------------- 
Equal mean values             `anova', `hotelling_test2',
                              `t_test_2',        `welch_test',
                              `wilcoxon_test', `z_test_2'
Equal medians                 `kruskal_wallis_test', `sign_test'
Equal variances               `bartlett_test', `manova',
                              `var_test'
Equal distributions           `chisquare_test_homogeneity',
                              `kolmogorov_smirnov_test_2',
                              `u_test'
Equal marginal frequencies    `mcnemar_test'
Equal success probabilities   `prop_test_2'
Independent observations      `chisquare_test_independence',
                              `run_test'
Uncorrelated observations     `cor_test'
Given mean value              `hotelling_test', `t_test', `z_test'
Observations from given       `kolmogorov_smirnov_test'
distribution                  
Regression                    `f_test_regression',
                              `t_test_regression'

   The tests return a p-value that describes the outcome of the test.
Assuming that the test hypothesis is true, the p-value is the
probability of obtaining a worse result than the observed one.  So
large p-values corresponds to a successful test.  Usually a test
hypothesis is accepted if the p-value exceeds 0.05.

 -- Function File: [PVAL, F, DF_B, DF_W] = anova (Y, G)
     Perform a one-way analysis of variance (ANOVA).  The goal is to
     test whether the population means of data taken from K different
     groups are all equal.

     Data may be given in a single vector Y with groups specified by a
     corresponding vector of group labels G (e.g., numbers from 1 to
     K).  This is the general form which does not impose any
     restriction on the number of data in each group or the group
     labels.

     If Y is a matrix and G is omitted, each column of Y is treated as
     a group.  This form is only appropriate for balanced ANOVA in
     which the numbers of samples from each group are all equal.

     Under the null of constant means, the statistic F follows an F
     distribution with DF_B and DF_W degrees of freedom.

     The p-value (1 minus the CDF of this distribution at F) is
     returned in PVAL.

     If no output argument is given, the standard one-way ANOVA table is
     printed.

 -- Function File: [PVAL, CHISQ, DF] = bartlett_test (X1, ...)
     Perform a Bartlett test for the homogeneity of variances in the
     data vectors X1, X2, ..., XK, where K > 1.

     Under the null of equal variances, the test statistic CHISQ
     approximately follows a chi-square distribution with DF degrees of
     freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, CHISQ, DF] = chisquare_test_homogeneity (X,
          Y, C)
     Given two samples X and Y, perform a chisquare test for
     homogeneity of the null hypothesis that X and Y come from the same
     distribution, based on the partition induced by the (strictly
     increasing) entries of C.

     For large samples, the test statistic CHISQ approximately follows a
     chisquare distribution with DF = `length (C)' degrees of freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, CHISQ, DF] = chisquare_test_independence (X)
     Perform a chi-square test for independence based on the contingency
     table X.  Under the null hypothesis of independence, CHISQ
     approximately has a chi-square distribution with DF degrees of
     freedom.

     The p-value (1 minus the CDF of this distribution at chisq) of the
     test is returned in PVAL.

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

 -- Function File:  cor_test (X, Y, ALT, METHOD)
     Test whether two samples X and Y come from uncorrelated
     populations.

     The optional argument string ALT describes the alternative
     hypothesis, and can be `"!="' or `"<>"' (non-zero), `">"' (greater
     than 0), or `"<"' (less than 0).  The default is the two-sided
     case.

     The optional argument string METHOD specifies which correlation
     coefficient to use for testing.  If METHOD is `"pearson"'
     (default), the (usual) Pearson's product moment correlation
     coefficient is used.  In this case, the data should come from a
     bivariate normal distribution.  Otherwise, the other two methods
     offer nonparametric alternatives.  If METHOD is `"kendall"', then
     Kendall's rank correlation tau is used.  If METHOD is
     `"spearman"', then Spearman's rank correlation rho is used.  Only
     the first character is necessary.

     The output is a structure with the following elements:

    PVAL
          The p-value of the test.

    STAT
          The value of the test statistic.

    DIST
          The distribution of the test statistic.

    PARAMS
          The parameters of the null distribution of the test statistic.

    ALTERNATIVE
          The alternative hypothesis.

    METHOD
          The method used for testing.

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

 -- Function File: [PVAL, F, DF_NUM, DF_DEN] = f_test_regression (Y, X,
          RR, R)
     Perform an F test for the null hypothesis rr * b = r in a classical
     normal regression model y = X * b + e.

     Under the null, the test statistic F follows an F distribution
     with DF_NUM and DF_DEN degrees of freedom.

     The p-value (1 minus the CDF of this distribution at F) is
     returned in PVAL.

     If not given explicitly, R = 0.

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

 -- Function File: [PVAL, TSQ] = hotelling_test (X, M)
     For a sample X from a multivariate normal distribution with unknown
     mean and covariance matrix, test the null hypothesis that `mean
     (X) == M'.

     Hotelling's T^2 is returned in TSQ.  Under the null, (n-p) T^2 /
     (p(n-1)) has an F distribution with p and n-p degrees of freedom,
     where n and p are the numbers of samples and variables,
     respectively.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, TSQ] = hotelling_test_2 (X, Y)
     For two samples X from multivariate normal distributions with the
     same number of variables (columns), unknown means and unknown
     equal covariance matrices, test the null hypothesis `mean (X) ==
     mean (Y)'.

     Hotelling's two-sample T^2 is returned in TSQ.  Under the null,

          (n_x+n_y-p-1) T^2 / (p(n_x+n_y-2))

     has an F distribution with p and n_x+n_y-p-1 degrees of freedom,
     where n_x and n_y are the sample sizes and p is the number of
     variables.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, KS] = kolmogorov_smirnov_test (X, DIST,
          PARAMS, ALT)
     Perform a Kolmogorov-Smirnov test of the null hypothesis that the
     sample X comes from the (continuous) distribution dist.  I.e., if
     F and G are the CDFs corresponding to the sample and dist,
     respectively, then the null is that F == G.

     The optional argument PARAMS contains a list of parameters of
     DIST.  For example, to test whether a sample X comes from a
     uniform distribution on [2,4], use

          kolmogorov_smirnov_test(x, "unif", 2, 4)

     DIST can be any string for which a function DIST_CDF that
     calculates the CDF of distribution DIST exists.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative F != G.  In this case, the test
     statistic KS follows a two-sided Kolmogorov-Smirnov distribution.
     If ALT is `">"', the one-sided alternative F > G is considered.
     Similarly for `"<"', the one-sided alternative F > G is
     considered.  In this case, the test statistic KS has a one-sided
     Kolmogorov-Smirnov distribution.  The default is the two-sided
     case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, KS, D] = kolmogorov_smirnov_test_2 (X, Y, ALT)
     Perform a 2-sample Kolmogorov-Smirnov test of the null hypothesis
     that the samples X and Y come from the same (continuous)
     distribution.  I.e., if F and G are the CDFs corresponding to the
     X and Y samples, respectively, then the null is that F == G.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative F != G.  In this case, the test
     statistic KS follows a two-sided Kolmogorov-Smirnov distribution.
     If ALT is `">"', the one-sided alternative F > G is considered.
     Similarly for `"<"', the one-sided alternative F < G is
     considered.  In this case, the test statistic KS has a one-sided
     Kolmogorov-Smirnov distribution.  The default is the two-sided
     case.

     The p-value of the test is returned in PVAL.

     The third returned value, D, is the test statistic, the maximum
     vertical distance between the two cumulative distribution
     functions.

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

 -- Function File: [PVAL, K, DF] = kruskal_wallis_test (X1, ...)
     Perform a Kruskal-Wallis one-factor "analysis of variance".

     Suppose a variable is observed for K > 1 different groups, and let
     X1, ..., XK be the corresponding data vectors.

     Under the null hypothesis that the ranks in the pooled sample are
     not affected by the group memberships, the test statistic K is
     approximately chi-square with DF = K - 1 degrees of freedom.

     If the data contains ties (some value appears more than once) K is
     divided by

     1 - SUM_TIES / (N^3 - N)

     where SUM_TIES is the sum of T^2 - T over each group of ties where
     T is the number of ties in the group and N is the total number of
     values in the input data.  For more info on this adjustment see
     "Use of Ranks in One-Criterion Variance Analysis" in Journal of
     the American Statistical Association, Vol. 47, No. 260 (Dec 1952)
     by William H. Kruskal and W. Allen Wallis.

     The p-value (1 minus the CDF of this distribution at K) is
     returned in PVAL.

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

 -- Function File:  manova (X, G)
     Perform a one-way multivariate analysis of variance (MANOVA).  The
     goal is to test whether the p-dimensional population means of data
     taken from K different groups are all equal.  All data are assumed
     drawn independently from p-dimensional normal distributions with
     the same covariance matrix.

     The data matrix is given by X.  As usual, rows are observations
     and columns are variables.  The vector G specifies the
     corresponding group labels (e.g., numbers from 1 to K).

     The LR test statistic (Wilks' Lambda) and approximate p-values are
     computed and displayed.

 -- Function File: [PVAL, CHISQ, DF] = mcnemar_test (X)
     For a square contingency table X of data cross-classified on the
     row and column variables, McNemar's test can be used for testing
     the null hypothesis of symmetry of the classification
     probabilities.

     Under the null, CHISQ is approximately distributed as chisquare
     with DF degrees of freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, Z] = prop_test_2 (X1, N1, X2, N2, ALT)
     If X1 and N1 are the counts of successes and trials in one sample,
     and X2 and N2 those in a second one, test the null hypothesis that
     the success probabilities P1 and P2 are the same.  Under the null,
     the test statistic Z approximately follows a standard normal
     distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative P1 != P2.  If ALT is `">"', the
     one-sided alternative P1 > P2 is used.  Similarly for `"<"', the
     one-sided alternative P1 < P2 is used.  The default is the
     two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, CHISQ] = run_test (X)
     Perform a chi-square test with 6 degrees of freedom based on the
     upward runs in the columns of X.  Can be used to test whether X
     contains independent data.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, B, N] = sign_test (X, Y, ALT)
     For two matched-pair samples X and Y, perform a sign test of the
     null hypothesis PROB (X > Y) == PROB (X < Y) == 1/2.  Under the
     null, the test statistic B roughly follows a binomial distribution
     with parameters `N = sum (X != Y)' and P = 1/2.

     With the optional argument `alt', the alternative of interest can
     be selected.  If ALT is `"!="' or `"<>"', the null hypothesis is
     tested against the two-sided alternative PROB (X < Y) != 1/2.  If
     ALT is `">"', the one-sided alternative PROB (X > Y) > 1/2 ("x is
     stochastically greater than y") is considered.  Similarly for
     `"<"', the one-sided alternative PROB (X > Y) < 1/2 ("x is
     stochastically less than y") is considered.  The default is the
     two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test (X, M, ALT)
     For a sample X from a normal distribution with unknown mean and
     variance, perform a t-test of the null hypothesis `mean (X) == M'.
     Under the null, the test statistic T follows a Student
     distribution with `DF = length (X) - 1' degrees of freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative `mean (X) > M' is considered.
     Similarly for "<", the one-sided alternative `mean (X) < M' is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test_2 (X, Y, ALT)
     For two samples x and y from normal distributions with unknown
     means and unknown equal variances, perform a two-sample t-test of
     the null hypothesis of equal means.  Under the null, the test
     statistic T follows a Student distribution with DF degrees of
     freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != mean (Y)'.  If ALT
     is `">"', the one-sided alternative `mean (X) > mean (Y)' is used.
     Similarly for `"<"', the one-sided alternative `mean (X) < mean
     (Y)' is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test_regression (Y, X, RR, R, ALT)
     Perform an t test for the null hypothesis `RR * B = R' in a
     classical normal regression model `Y = X * B + E'.  Under the
     null, the test statistic T follows a T distribution with DF
     degrees of freedom.

     If R is omitted, a value of 0 is assumed.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `RR * B != R'.  If ALT is `">"',
     the one-sided alternative `RR * B > R' is used.  Similarly for
     "<", the one-sided alternative `RR * B < R' is used.  The default
     is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = u_test (X, Y, ALT)
     For two samples X and Y, perform a Mann-Whitney U-test of the null
     hypothesis PROB (X > Y) == 1/2 == PROB (X < Y).  Under the null,
     the test statistic Z approximately follows a standard normal
     distribution.  Note that this test is equivalent to the Wilcoxon
     rank-sum test.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative PROB (X > Y) != 1/2.  If ALT is
     `">"', the one-sided alternative PROB (X > Y) > 1/2 is considered.
     Similarly for `"<"', the one-sided alternative PROB (X > Y) < 1/2
     is considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, F, DF_NUM, DF_DEN] = var_test (X, Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and unknown variances, perform an F-test of the null
     hypothesis of equal variances.  Under the null, the test statistic
     F follows an F-distribution with DF_NUM and DF_DEN degrees of
     freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `var (X) != var (Y)'.  If ALT is
     `">"', the one-sided alternative `var (X) > var (Y)' is used.
     Similarly for "<", the one-sided alternative `var (X) > var (Y)'
     is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = welch_test (X, Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and unknown and not necessarily equal variances, perform a
     Welch test of the null hypothesis of equal means.  Under the null,
     the test statistic T approximately follows a Student distribution
     with DF degrees of freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative mean(x) > M is considered.
     Similarly for `"<"', the one-sided alternative mean(x) < M is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = wilcoxon_test (X, Y, ALT)
     For two matched-pair sample vectors X and Y, perform a Wilcoxon
     signed-rank test of the null hypothesis PROB (X > Y) == 1/2.
     Under the null, the test statistic Z approximately follows a
     standard normal distribution when N > 25.

     *Caution:* This function assumes a normal distribution for Z and
     thus is invalid for N <= 25.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative PROB (X > Y) != 1/2.  If alt is
     `">"', the one-sided alternative PROB (X > Y) > 1/2 is considered.
     Similarly for `"<"', the one-sided alternative PROB (X > Y) < 1/2
     is considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = z_test (X, M, V, ALT)
     Perform a Z-test of the null hypothesis `mean (X) == M' for a
     sample X from a normal distribution with unknown mean and known
     variance V.  Under the null, the test statistic Z follows a
     standard normal distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative `mean (X) > M' is considered.
     Similarly for `"<"', the one-sided alternative `mean (X) < M' is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

     If no output argument is given, the p-value of the test is
     displayed along with some information.

 -- Function File: [PVAL, Z] = z_test_2 (X, Y, V_X, V_Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and known variances V_X and V_Y, perform a Z-test of the
     hypothesis of equal means.  Under the null, the test statistic Z
     follows a standard normal distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != mean (Y)'.  If alt
     is `">"', the one-sided alternative `mean (X) > mean (Y)' is used.
     Similarly for `"<"', the one-sided alternative `mean (X) < mean
     (Y)' is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

     If no output argument is given, the p-value of the test is
     displayed along with some information.


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

26.7 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
----------------------------------------------------- 
Beta Distribution             `betarnd'
Binomial Distribution         `binornd'
Cauchy Distribution           `cauchy_rnd'
Chi-Square Distribution       `chi2rnd'
Univariate Discrete           `discrete_rnd'
Distribution                  
Empirical Distribution        `empirical_rnd'
Exponential Distribution      `exprnd'
F Distribution                `frnd'
Gamma Distribution            `gamrnd'
Geometric Distribution        `geornd'
Hypergeometric Distribution   `hygernd'
Laplace Distribution          `laplace_rnd'
Logistic Distribution         `logistic_rnd'
Log-Normal Distribution       `lognrnd'
Pascal Distribution           `nbinrnd'
Univariate Normal             `normrnd'
Distribution                  
Poisson Distribution          `poissrnd'
Standard Normal Distribution  `stdnormal_rnd'
t (Student) Distribution      `trnd'
Univariate Discrete           `unidrnd'
Distribution                  
Uniform Distribution          `unifrnd'
Weibull Distribution          `wblrnd'
Wiener Process                `wienrnd'

 -- Function File:  betarnd (A, B)
 -- Function File:  betarnd (A, B, R)
 -- Function File:  betarnd (A, B, R, C, ...)
 -- Function File:  betarnd (A, B, [SZ])
     Return a matrix of random samples from the Beta distribution with
     parameters A and B.

     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 A and B.

 -- Function File:  binornd (N, P)
 -- Function File:  binornd (N, P, R)
 -- Function File:  binornd (N, P, R, C, ...)
 -- Function File:  binornd (N, P, [SZ])
     Return a matrix of random samples from the binomial distribution
     with parameters N and P, where N is the number of trials and P is
     the probability of success.

     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 N and P.

 -- Function File:  cauchy_rnd (LOCATION, SCALE)
 -- Function File:  cauchy_rnd (LOCATION, SCALE, R)
 -- Function File:  cauchy_rnd (LOCATION, SCALE, R, C, ...)
 -- Function File:  cauchy_rnd (LOCATION, SCALE, [SZ])
     Return a matrix of random samples from the Cauchy distribution with
     parameters LOCATION and SCALE.

     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 LOCATION and SCALE.

 -- Function File:  chi2rnd (N)
 -- Function File:  chi2rnd (N, R)
 -- Function File:  chi2rnd (N, R, C, ...)
 -- Function File:  chi2rnd (N, [SZ])
     Return a matrix of random samples from the chi-square distribution
     with N degrees of freedom.

     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 size
     of N.

 -- Function File:  discrete_rnd (V, P)
 -- Function File:  discrete_rnd (V, P, R)
 -- Function File:  discrete_rnd (V, P, R, C, ...)
 -- Function File:  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.

 -- Function File:  empirical_rnd (DATA)
 -- Function File:  empirical_rnd (DATA, R)
 -- Function File:  empirical_rnd (DATA, R, C, ...)
 -- Function File:  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.

 -- Function File:  exprnd (LAMBDA)
 -- Function File:  exprnd (LAMBDA, R)
 -- Function File:  exprnd (LAMBDA, R, C, ...)
 -- Function File:  exprnd (LAMBDA, [SZ])
     Return a matrix of random samples from the exponential
     distribution with mean LAMBDA.

     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 size
     of LAMBDA.

 -- Function File:  frnd (M, N)
 -- Function File:  frnd (M, N, R)
 -- Function File:  frnd (M, N, R, C, ...)
 -- Function File:  frnd (M, N, [SZ])
     Return a matrix of random samples from the F distribution with M
     and N degrees of freedom.

     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 M and N.

 -- Function File:  gamrnd (A, B)
 -- Function File:  gamrnd (A, B, R)
 -- Function File:  gamrnd (A, B, R, C, ...)
 -- Function File:  gamrnd (A, B, [SZ])
     Return a matrix of random samples from the Gamma distribution with
     shape parameter A and scale B.

     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 A and B.

 -- Function File:  geornd (P)
 -- Function File:  geornd (P, R)
 -- Function File:  geornd (P, R, C, ...)
 -- Function File:  geornd (P, [SZ])
     Return a matrix of random samples from the geometric distribution
     with parameter 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 size
     of P.

 -- Function File:  hygernd (T, M, N)
 -- Function File:  hygernd (T, M, N, R)
 -- Function File:  hygernd (T, M, N, R, C, ...)
 -- Function File:  hygernd (T, M, N, [SZ])
     Return a matrix of random samples from the hypergeometric
     distribution with parameters T, M, and N.

     The parameters T, M, and N must be positive integers with M and N
     not greater than T.

     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 T, M, and N.

 -- Function File:  laplace_rnd (R)
 -- Function File:  laplace_rnd (R, C, ...)
 -- Function File:  laplace_rnd ([SZ])
     Return a matrix of random samples from the Laplace distribution.

     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.

 -- Function File:  logistic_rnd (R)
 -- Function File:  logistic_rnd (R, C, ...)
 -- Function File:  logistic_rnd ([SZ])
     Return a matrix of random samples from the logistic distribution.

     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.

 -- Function File:  lognrnd (MU, SIGMA)
 -- Function File:  lognrnd (MU, SIGMA, R)
 -- Function File:  lognrnd (MU, SIGMA, R, C, ...)
 -- Function File:  lognrnd (MU, SIGMA, [SZ])
     Return a matrix of random samples from the lognormal distribution
     with parameters MU and SIGMA.

     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 MU and SIGMA.

 -- Function File:  nbinrnd (N, P)
 -- Function File:  nbinrnd (N, P, R)
 -- Function File:  nbinrnd (N, P, R, C, ...)
 -- Function File:  nbinrnd (N, P, [SZ])
     Return a matrix of random samples from the negative binomial
     distribution with parameters N and 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 N and P.

 -- Function File:  normrnd (MU, SIGMA)
 -- Function File:  normrnd (MU, SIGMA, R)
 -- Function File:  normrnd (MU, SIGMA, R, C, ...)
 -- Function File:  normrnd (MU, SIGMA, [SZ])
     Return a matrix of random samples from the normal distribution with
     parameters mean MU and standard deviation SIGMA.

     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 MU and SIGMA.

 -- Function File:  poissrnd (LAMBDA)
 -- Function File:  poissrnd (LAMBDA, R)
 -- Function File:  poissrnd (LAMBDA, R, C, ...)
 -- Function File:  poissrnd (LAMBDA, [SZ])
     Return a matrix of random samples from the Poisson distribution
     with parameter LAMBDA.

     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 size
     of LAMBDA.

 -- Function File:  stdnormal_rnd (R)
 -- Function File:  stdnormal_rnd (R, C, ...)
 -- Function File:  stdnormal_rnd ([SZ])
     Return a matrix of random samples from the standard normal
     distribution (mean = 0, standard deviation = 1).

     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.

 -- Function File:  trnd (N)
 -- Function File:  trnd (N, R)
 -- Function File:  trnd (N, R, C, ...)
 -- Function File:  trnd (N, [SZ])
     Return a matrix of random samples from the t (Student)
     distribution with N degrees of freedom.

     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 size
     of N.

 -- Function File:  unidrnd (N)
 -- Function File:  unidrnd (N, R)
 -- Function File:  unidrnd (N, R, C, ...)
 -- Function File:  unidrnd (N, [SZ])
     Return a matrix of random samples from the discrete uniform
     distribution which assumes the integer values 1-N with equal
     probability.  N may be a scalar or a multi-dimensional array.

     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 size
     of N.

 -- Function File:  unifrnd (A, B)
 -- Function File:  unifrnd (A, B, R)
 -- Function File:  unifrnd (A, B, R, C, ...)
 -- Function File:  unifrnd (A, B, [SZ])
     Return a matrix of random samples from the uniform distribution on
     [A, B].

     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 A and B.

 -- Function File:  wblrnd (SCALE, SHAPE)
 -- Function File:  wblrnd (SCALE, SHAPE, R)
 -- Function File:  wblrnd (SCALE, SHAPE, R, C, ...)
 -- Function File:  wblrnd (SCALE, SHAPE, [SZ])
     Return a matrix of random samples from the Weibull distribution
     with parameters SCALE and SHAPE.

     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 SCALE and SHAPE.

 -- Function File:  wienrnd (T, D, N)
     Return a simulated realization of the D-dimensional Wiener Process
     on the interval [0, T].  If D is omitted, D = 1 is used.  The
     first column of the return matrix contains time, the remaining
     columns contain the Wiener process.

     The optional parameter N gives the number of summands used for
     simulating the process over an interval of length 1.  If N is
     omitted, N = 1000 is used.


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

27 Sets
*******

Octave has a limited number of functions for managing sets of data,
where a set is defined as a collection of unique elements.  In Octave a
set is represented as a vector of numbers.

 -- Function File:  unique (X)
 -- Function File:  unique (X, "rows")
 -- Function File:  unique (..., "first")
 -- Function File:  unique (..., "last")
 -- Function File: [Y, I, J] = unique (...)
     Return the unique elements of X, sorted in ascending order.  If
     the input X is a vector then the output is also a vector with the
     same orientation (row or column) as the input.  For a matrix input
     the output is always a column vector.  X may also be a cell array
     of strings.

     If the optional argument `"rows"' is supplied, return the unique
     rows of X, sorted in ascending order.

     If requested, return index vectors I and J such that `x(i)==y' and
     `y(j)==x'.

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

     *See also:* *note union: doc-union, *note intersect:
     doc-intersect, *note setdiff: doc-setdiff, *note setxor:
     doc-setxor, *note ismember: doc-ismember.

* Menu:

* Set Operations::


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

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

Octave supports the basic set operations.  That is, Octave can compute
the union, intersection, and difference of two sets.  Octave also
supports the _Exclusive Or_ set operation, and membership
determination.  The functions for set operations all work in pretty
much the same way.  As an example, assume that `x' and `y' contains two
sets, then

     union(x, y)

computes the union of the two sets.

 -- Function File: TF = ismember (A, S)
 -- Function File: [TF, S_IDX] = ismember (A, S)
 -- Function File: [TF, S_IDX] = ismember (A, S, "rows")
     Return a logical matrix TF with the same shape as A which is true
     (1) if `A(i,j)' is in S and false (0) if it is not.  If a second
     output argument is requested, the index into S of each of the
     matching elements 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, 0]
               => s_idx = [1, 0]

     With the optional third argument `"rows"', and matrices A and S
     with the same number of columns, compare rows in A with the rows
     in S.

          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 unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setxor: doc-setxor, *note
     setdiff: doc-setdiff.

 -- Function File:  union (A, B)
 -- Function File:  union (A, B, "rows")
     Return the set of elements that are in either of the sets A and B.
     A, B may be cell arrays of string(s).  For example:

          union ([1, 2, 4], [2, 3, 5])
              => [1, 2, 3, 4, 5]

     If the optional third input argument is the string "rows" each row
     of the matrices A and B will be considered an element of sets.
     For example:

          union ([1, 2; 2, 3], [1, 2; 3, 4], "rows")
             =>  1   2
                 2   3
                 3   4

 -- Function File: [C, IA, IB] = union (A, B)
     Return index vectors IA and IB such that `a(ia)' and `b(ib)' are
     disjoint sets whose union is C.

     *See also:* *note intersect: doc-intersect, *note setdiff:
     doc-setdiff, *note unique: doc-unique.

 -- Function File:  intersect (A, B)
 -- Function File: [C, IA, IB] = intersect (A, B)
     Return the elements in both A and B, sorted in ascending order.
     If A and B are both column vectors return a column vector,
     otherwise return a row vector.  A, B may be cell arrays of
     string(s).

     Return index vectors IA and IB such that `a(ia)==c' and `b(ib)==c'.


*See also:* *note unique: doc-unique, *note union: doc-union, *note
setxor: doc-setxor, *note setdiff: doc-setdiff, *note ismember:
doc-ismember.

 -- Function File:  setdiff (A, B)
 -- Function File:  setdiff (A, B, "rows")
 -- Function File: [C, I] = setdiff (A, B)
     Return the elements in A that are not in B, sorted in ascending
     order.  If A and B are both column vectors return a column vector,
     otherwise return a row vector.  A, B may be cell arrays of
     string(s).

     Given the optional third argument `"rows"', return the rows in A
     that are not in B, sorted in ascending order by rows.

     If requested, return I such that `c = a(i)'.

     *See also:* *note unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setxor: doc-setxor, *note
     ismember: doc-ismember.

 -- Function File:  setxor (A, B)
 -- Function File:  setxor (A, B, 'rows')
 -- Function File: [C, IA, IB] = setxor (A, B)
     Return the elements exclusive to A or B, sorted in ascending
     order.  If A and B are both column vectors return a column vector,
     otherwise return a row vector.  A, B may be cell arrays of
     string(s).

     With three output arguments, return index vectors IA and IB such
     that `a(ia)' and `b(ib)' are disjoint sets whose union is C.

     *See also:* *note unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setdiff: doc-setdiff, *note
     ismember: doc-ismember.

 -- Function File:  powerset (A)
 -- Function File:  powerset (A, "rows")
     Return a cell array containing all subsets of the set A.


*See also:* *note unique: doc-unique, *note union: doc-union, *note
setxor: doc-setxor, *note setdiff: doc-setdiff, *note ismember:
doc-ismember.


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.

 -- Function File: Y = polyval (P, X)
 -- Function File: Y = polyval (P, X, [], MU)
     Evaluate the polynomial P at the specified values of X.  When MU
     is present, evaluate the polynomial for (X-MU(1))/MU(2).  If X is
     a vector or matrix, the polynomial is evaluated for each of the
     elements of X.

 -- Function File: [Y, DY] = polyval (P, X, S)
 -- Function File: [Y, DY] = polyval (P, X, S, MU)
     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: doc-polyvalm, *note polyaffine:
     doc-polyaffine, *note polyfit: doc-polyfit, *note roots:
     doc-roots, *note poly: doc-poly.

 -- Function File:  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: doc-polyval, *note roots: doc-roots,
     *note poly: doc-poly.


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.

 -- Function File:  roots (V)
     For a vector V with N components, return the roots of the
     polynomial

          v(1) * z^(N-1) + ... + v(N-1) * z + v(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: doc-poly, *note compan: doc-compan, *note
     fzero: doc-fzero.

 -- Function File:  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: doc-roots, *note poly: doc-poly, *note
     eig: doc-eig.

 -- Function File: [MULTP, IDXP] = mpoles (P)
 -- Function File: [MULTP, IDXP] = mpoles (P, TOL)
 -- Function File: [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: doc-residue, *note poly: doc-poly,
     *note roots: doc-roots, *note conv: doc-conv, *note deconv:
     doc-deconv.


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

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

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

     The output convolution is a vector with length equal to `length
     (A) + length (B) - 1'.  When A and B are the coefficient vectors
     of two polynomials, the convolution represents the coefficient
     vector of the product polynomial.

     The optional SHAPE argument may be

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

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

     *See also:* *note deconv: doc-deconv, *note conv2: doc-conv2,
     *note convn: doc-convn, *note fftconv: doc-fftconv.

 -- Loadable Function: C = convn (A, B)
 -- Loadable Function: 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: doc-conv2, *note conv: doc-conv.

 -- Function File:  deconv (Y, A)
     Deconvolve two vectors.

     `[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: doc-conv, *note residue: doc-residue.

 -- Loadable Function:  conv2 (A, B)
 -- Loadable Function:  conv2 (V1, V2, M)
 -- Loadable Function:  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: doc-conv, *note convn: doc-convn.

 -- Function File: Q = polygcd (B, A)
 -- Function File: 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: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue.

 -- Function File: [R, P, K, E] = residue (B, A)
 -- Function File: [B, A] = residue (R, P, K)
 -- Function File: [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.

          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: doc-mpoles, *note poly: doc-poly, *note
     roots: doc-roots, *note conv: doc-conv, *note deconv: doc-deconv.


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

 -- Function File:  polyder (P)
 -- Function File: [K] = polyder (A, B)
 -- Function File: [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: doc-polyint, *note polyval:
     doc-polyval, *note polyreduce: doc-polyreduce.

 -- Function File:  polyint (P)
 -- Function File:  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: doc-polyder, *note polyval: doc-polyval.

 -- Function File:  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: doc-polyval, *note polyfit: doc-polyfit.


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 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.

 -- Function File: P = polyfit (X, Y, N)
 -- Function File: [P, S] = polyfit (X, Y, N)
 -- Function File: [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]'.

     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.

    `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.

     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: doc-polyval, *note polyaffine:
     doc-polyaffine, *note roots: doc-roots, *note vander: doc-vander,
     *note zscore: doc-zscore.

   In situations where a single polynomial isn't good enough, a solution
is to use several polynomials pieced together.  The function `mkpp'
creates a piecewise polynomial, `ppval' evaluates the function created
by `mkpp', and `unmkpp' returns detailed information about the function.

   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);

 -- Function File: PP = mkpp (BREAKS, COEFS)
 -- Function File: 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 x 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).

     COEFS may also be a multi-dimensional array, specifying a
     vector-valued or array-valued polynomial.  In that case the
     polynomial order 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 any case COEFS
     is reshaped to a 2-D matrix of size `[NI*prod(D M)] '

     *See also:* *note unmkpp: doc-unmkpp, *note ppval: doc-ppval,
     *note spline: doc-spline, *note pchip: doc-pchip, *note ppder:
     doc-ppder, *note ppint: doc-ppint, *note ppjumps: doc-ppjumps.

 -- Function File: [X, P, N, K, D] = unmkpp (PP)
     Extract the components of a piecewise polynomial structure PP.
     The components are:

    X
          Sample points.

    P
          Polynomial coefficients for points in sample interval.  `P
          (I, :)' contains the coefficients for the polynomial over
          interval I ordered from highest to lowest.  If `D > 1', `P
          (R, I, :)' contains the coefficients for the r-th polynomial
          defined on interval I.

    N
          Number of polynomial pieces.

    K
          Order of the polynomial plus 1.

    D
          Number of polynomials defined for each interval.

     *See also:* *note mkpp: doc-mkpp, *note ppval: doc-ppval, *note
     spline: doc-spline, *note pchip: doc-pchip.

 -- Function File: 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: doc-mkpp, *note unmkpp: doc-unmkpp, *note
     spline: doc-spline, *note pchip: doc-pchip.

 -- Function File: ppd = ppder (pp)
 -- Function File: 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: doc-mkpp, *note ppval: doc-ppval, *note
     ppint: doc-ppint.

 -- Function File: PPI = ppint (PP)
 -- Function File: 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: doc-mkpp, *note ppval: doc-ppval, *note
     ppder: doc-ppder.

 -- Function File: 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: doc-mkpp.


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

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

 -- Function File:  poly (A)
 -- Function File:  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: doc-roots, *note eig: doc-eig.

 -- Function File:  polyout (C)
 -- Function File:  polyout (C, X)
 -- Function File: STR = polyout (...)
     Write formatted polynomial

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

     and return it as a string or write it to the screen (if NARGOUT is
     zero).  X defaults to the string `"s"'.

     *See also:* *note polyreduce: doc-polyreduce.

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

     *See also:* *note polyout: doc-polyout.


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
further methods.

 -- Function File: YI = interp1 (X, Y, XI)
 -- Function File: YI = interp1 (Y, XI)
 -- Function File: YI = interp1 (..., METHOD)
 -- Function File: YI = interp1 (..., EXTRAP)
 -- Function File: PP = interp1 (..., 'pp')
     One-dimensional interpolation.  Interpolate Y, defined at the
     points X, at the points XI.  The sample points X must be
     monotonic.  If not specified, X is taken to be the indices of Y.
     If Y is an array, treat the columns of Y separately.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors

    'pchip'
          Piecewise cubic Hermite interpolating polynomial

    'cubic'
          Cubic interpolation (same as `pchip')

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve

     Appending '*' to the start of the above method 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.  If EXTRAP is a number, replace values beyond the
     endpoints with that number.  If EXTRAP is missing, assume NA.

     If the string argument 'pp' is specified, then XI should not be
     supplied and `interp1' returns the piecewise polynomial that 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
     should be at most 2 consecutive points with the same value.  The
     discontinuous interpolant is right-continuous if X is increasing,
     left-continuous if it is decreasing.  Discontinuities are
     (currently) only allowed for "nearest" and "linear" methods; in
     all other cases, X must be strictly monotonic.

     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);
          spl = interp1 (xp, yp, xf, "spline");
          cub = interp1 (xp, yp, xf, "cubic");
          near = interp1 (xp, yp, xf, "nearest");
          plot (xf, yf, "r", xf, lin, "g", xf, spl, "b",
                xf, cub, "c", xf, near, "m", xp, yp, "r*");
          legend ("original", "linear", "spline", "cubic", "nearest");

     *See also:* *note interpft: doc-interpft.

   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');

   A simplified version of `interp1' that performs only linear
interpolation is available in `interp1q'.  This argument is slightly
faster than `interp1' as to performs little error checking.

 -- Function File: YI = interp1q (X, Y, XI)
     One-dimensional linear interpolation without error checking.
     Interpolates Y, defined at the points X, at the points XI.  The
     sample points X must be a strictly monotonically increasing column
     vector.  If Y is an array, treat the columns of Y separately.  If
     Y is a vector, it must be a column vector of the same length as X.

     Values of XI beyond the endpoints of the interpolation result in
     NA being returned.

     Note that the error checking is only a significant portion of the
     execution time of this `interp1' if the size of the input arguments
     is relatively small.  Therefore, the benefit of using `interp1q'
     is relatively small.

     *See also:* *note interp1: doc-interp1.

   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.

 -- Function File:  interpft (X, N)
 -- Function File:  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 an
     array, then operate along each column of the array separately.  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: doc-interp1.

   There are two significant limitations on Fourier interpolation.
Firstly, the function signal is assumed to be periodic, and so
non-periodic signals will be poorly represented at the edges.
Secondly, 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 additional the support function `spline' and `lookup' that
underlie the `interp1' function can be called directly.  *note Finding
Elements and Checking Conditions::

 -- Function File: PP = spline (X, Y)
 -- Function File: 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 opposite to `interp1' but
     is done for MATLAB compatibility.

     *See also:* *note pchip: doc-pchip, *note ppval: doc-ppval, *note
     mkpp: doc-mkpp, *note unmkpp: doc-unmkpp.


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::.

 -- Function File: ZI = interp2 (X, Y, Z, XI, YI)
 -- Function File: ZI = interp2 (Z, XI, YI)
 -- Function File: ZI = interp2 (Z, N)
 -- Function File: ZI = interp2 (..., METHOD)
 -- Function File: ZI = interp2 (..., METHOD, EXTRAPVAL)
     Two-dimensional interpolation.  X, Y and Z describe a surface
     function.  If X and Y are vectors their length must correspondent
     to the size of Z.  X and Y must be monotonic.  If they are
     matrices they must have the `meshgrid' format.

    `interp2 (X, Y, Z, XI, YI, ...)'
          Returns a matrix corresponding to the points described by the
          matrices XI, YI.

          If the last argument is a string, the interpolation method can
          be specified.  The method can be 'linear', 'nearest' or
          'cubic'.  If it is omitted 'linear' interpolation is assumed.

    `interp2 (Z, XI, YI)'
          Assumes `X = 1:rows (Z)' and `Y = 1:columns (Z)'

    `interp2 (Z, N)'
          Interleaves the matrix Z n-times.  If N is omitted a value of
          `N = 1' is assumed.

     The variable METHOD defines the method to use for the
     interpolation.  It can take one of the following values

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'pchip'
          Piecewise cubic Hermite interpolating polynomial.

    'cubic'
          Cubic interpolation from four nearest neighbors.

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     If a scalar value EXTRAPVAL is defined as the final value, then
     values outside the mesh as set to this value.  Note that in this
     case METHOD must be defined as well.  If EXTRAPVAL is not defined
     then NA is assumed.

     *See also:* *note interp1: doc-interp1.

 -- Function File: VI = interp3 (X, Y, Z, V, XI, YI, ZI)
 -- Function File: VI = interp3 (V, XI, YI, ZI)
 -- Function File: VI = interp3 (V, M)
 -- Function File: VI = interp3 (V)
 -- Function File: VI = interp3 (..., METHOD)
 -- Function File: VI = interp3 (..., METHOD, EXTRAPVAL)
     Perform 3-dimensional interpolation.  Each element of the
     3-dimensional array V represents a value at a location given by
     the parameters X, Y, and Z.  The parameters X, X, and Z are either
     3-dimensional arrays of the same size as the array V in the
     'meshgrid' format or vectors.  The parameters XI, etc.  respect a
     similar format to X, etc., and they represent the points at which
     the array VI is interpolated.

     If X, Y, Z are omitted, they are assumed to be `x = 1 : size (V,
     2)', `y = 1 : size (V, 1)' and `z = 1 : size (V, 3)'.  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'.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'cubic'
          Cubic interpolation from four nearest neighbors (not
          implemented yet).

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     The default method is 'linear'.

     If EXTRAP is the string 'extrap', then extrapolate values beyond
     the endpoints.  If EXTRAP is a number, replace values beyond the
     endpoints with that number.  If EXTRAP is missing, assume NA.

     *See also:* *note interp1: doc-interp1, *note interp2:
     doc-interp2, *note spline: doc-spline, *note meshgrid:
     doc-meshgrid.

 -- Function File: VI = interpn (X1, X2, ..., V, Y1, Y2, ...)
 -- Function File: VI = interpn (V, Y1, Y2, ...)
 -- Function File: VI = interpn (V, M)
 -- Function File: VI = interpn (V)
 -- Function File: VI = interpn (..., METHOD)
 -- Function File: 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'.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'cubic'
          Cubic interpolation from four nearest neighbors (not
          implemented yet).

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     The default method is 'linear'.

     If EXTRAPVAL is the scalar value, use it to replace the values
     beyond the endpoints with that number.  If EXTRAPVAL is missing,
     assume NA.

     *See also:* *note interp1: doc-interp1, *note interp2:
     doc-interp2, *note spline: doc-spline, *note ndgrid: doc-ndgrid.

   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.

   In additional the support function `bicubic' that underlies the
cubic interpolation of `interp2' function can be called directly.

 -- Function File: ZI = bicubic (X, Y, Z, XI, YI, EXTRAPVAL)
     Return a matrix ZI corresponding to the bicubic interpolations at
     XI and YI of the data supplied as X, Y and Z.  Points outside the
     grid are set to EXTRAPVAL.

     See `http://wiki.woodpecker.org.cn/moin/Octave/Bicubic' for
     further information.

     *See also:* *note interp2: doc-interp2.


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::

   ---------- 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.

 -- Function File:  delaunay (X, Y)
 -- Function File: TRI = delaunay (X, Y)
 -- Function File: TRI = delaunay (X, Y, OPTIONS)
     Compute the Delaunay triangulation for a 2-D set of points.  The
     return value TRI is a set of triangles which satisfies the
     Delaunay circum-circle criterion, i.e., only a single 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.

     An optional third 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", "Qz"}'.

     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 no output argument is specified the resulting Delaunay
     triangulation is plotted along with the original set of points.

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

     *See also:* *note delaunay3: doc-delaunay3, *note delaunayn:
     doc-delaunayn, *note convhull: doc-convhull, *note voronoi:
     doc-voronoi.

   The 3- and N-dimensional extension of the Delaunay triangulation are
given by `delaunay3' and `delaunayn' respectively.  `delaunay3' 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.

 -- Function File: TETR = delaunay3 (X, Y, Z)
 -- Function File: TETR = delaunay3 (X, Y, Z, OPTIONS)
     Compute the Delaunay triangulation for a 3-D set of points.  The
     return value TETR is a set of tetrahedrons which satisfies the
     Delaunay circum-circle criterion, i.e., only a single data point
     from [X, Y, Z] is within the circum-circle of the defining
     tetrahedron.

     The set of tetrahedrons TETR 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.

     An optional fourth 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", "Qz"}'.

     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: doc-delaunay, *note delaunayn:
     doc-delaunayn, *note convhull: doc-convhull, *note voronoi:
     doc-voronoi.

 -- Function File: T = delaunayn (PTS)
 -- Function File: 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", "Qz"}'

        * 4-D and higher: OPTIONS = `{"Qt", "Qbb", "Qc", "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 delaunay: doc-delaunay, *note delaunay3:
     doc-delaunay3, *note convhulln: doc-convhulln, *note voronoin:
     doc-voronoin.

   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.

 -- Function File:  triplot (TRI, X, Y)
 -- Function File:  triplot (TRI, X, Y, LINESPEC)
 -- Function File: H = triplot (...)
     Plot a triangular mesh in 2D.  The variable TRI is the triangular
     meshing of the points `(X, Y)' which is returned from `delaunay'.
     If given, LINESPEC determines the properties to use for the lines.

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

     *See also:* *note plot: doc-plot, *note trimesh: doc-trimesh,
     *note trisurf: doc-trisurf, *note delaunay: doc-delaunay.

 -- Function File:  trimesh (TRI, X, Y, Z)
 -- Function File: H = trimesh (...)
     Plot a triangular mesh in 3D.  The variable TRI is the triangular
     meshing of the points `(X, Y)' which is returned from `delaunay'.
     The variable Z is value at the point `(X, Y)'.

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

     *See also:* *note triplot: doc-triplot, *note trisurf:
     doc-trisurf, *note delaunay3: doc-delaunay3.

 -- Function File:  trisurf (TRI, X, Y, Z)
 -- Function File: H = trisurf (...)
     Plot a triangular surface in 3D.  The variable TRI is the
     triangular meshing of the points `(X, Y)' which is returned from
     `delaunay'.  The variable Z is value at the point `(X, Y)'.

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

     *See also:* *note triplot: doc-triplot, *note trimesh:
     doc-trimesh, *note delaunay3: doc-delaunay3.

   The difference between `triplot', and `trimesh' or `triplot', 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 = sum (BETA(1:N+1) * T(1:N+1),:)

where there are `N + 1' values `BETA(I)' that together as a vector
represent the Barycentric coordinates of the point P.  To ensure a
unique solution for the values of `BETA(I)' an additional criteria of

     sum (BETA(1:N+1)) == 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.

 -- Loadable Function: 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: doc-delaunay, *note delaunayn:
     doc-delaunayn.

 -- Function File: [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: doc-delaunay, *note delaunayn:
     doc-delaunayn.

   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, 1];

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 vertexes of the
N-simplex within which the desired point is found.

 -- Function File: IDX = dsearch (X, Y, TRI, XI, YI)
 -- Function File: IDX = dsearch (X, Y, TRI, XI, YI, S)
     Return the index IDX or 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: doc-dsearchn, *note tsearch:
     doc-tsearch.

 -- Function File: IDX = dsearchn (X, TRI, XI)
 -- Function File: IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- Function File: IDX = dsearchn (X, XI)
 -- Function File: [IDX, D] = dsearchn (...)
     Return the index IDX or 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: doc-dsearch, *note tsearch: doc-tsearch.

   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 vertexes of the Voronoi tessellation are the
centers of the circum-circles of the simplices of the Delaunay
tessellation.

 -- Function File:  voronoi (X, Y)
 -- Function File:  voronoi (X, Y, OPTIONS)
 -- Function File:  voronoi (..., "linespec")
 -- Function File:  voronoi (HAX, ...)
 -- Function File: H = voronoi (...)
 -- Function File: [VX, VY] = voronoi (...)
     Plot the Voronoi diagram of points `(X, Y)'.  The Voronoi facets
     with points at infinity are not drawn.

     If "linespec" is given it is used to set the color and line style
     of the plot.  If an axis graphics handle HAX is supplied then the
     Voronoi diagram is drawn on the specified axis rather than in a
     new figure.

     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 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: doc-voronoin, *note delaunay:
     doc-delaunay, *note convhull: doc-convhull.

 -- Function File: [C, F] = voronoin (PTS)
 -- Function File: [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'.

     *See also:* *note voronoi: doc-voronoi, *note convhulln:
     doc-convhulln, *note delaunayn: doc-delaunayn.

   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.

 -- Function File:  polyarea (X, Y)
 -- Function File:  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'

 -- Function File: AREA = rectint (A, B)
     Compute the area of intersection of rectangles in A and rectangles
     in B.  Rectangles are defined as [x y width height] where x and y
     are the minimum values of the two orthogonal dimensions.

     If A or B are matrices, 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: doc-polyarea.

 -- Function File: [IN, ON] = inpolygon (X, Y, XV, YV)
     For a polygon defined by vertex points `(XV, YV)', determine if
     the points `(X, Y)' are inside or outside the polygon.  The
     variables X, Y, must have the same dimension.  The optional output
     ON gives the points that are on the polygon.


   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.

 -- Function File: H = convhull (X, Y)
 -- Function File: H = convhull (X, Y, OPTIONS)
     Compute the convex hull of the set of points defined by the
     vectors X and Y.  The hull H is an index vector into the set of
     points and specifies which points form the enclosing hull.

     An optional third 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.

     *See also:* *note convhulln: doc-convhulln, *note delaunay:
     doc-delaunay, *note voronoi: doc-voronoi.

 -- Loadable Function: H = convhulln (PTS)
 -- Loadable Function: H = convhulln (PTS, OPTIONS)
 -- Loadable Function: [H, V] = convhulln (...)
     Compute the convex hull of the set of points PTS which 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: doc-convhull, *note delaunayn:
     doc-delaunayn, *note voronoin: doc-voronoin.

   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,  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', `delaunay3' 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'.

 -- Function File: ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- Function File: [XI, YI, ZI] = griddata (X, Y, Z, XI, YI, METHOD)
     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 delaunay: doc-delaunay.

 -- Function File: 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"'.

     *See also:* *note griddata: doc-griddata, *note griddatan:
     doc-griddatan, *note delaunayn: doc-delaunayn.

 -- Function File: 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"'.

     *See also:* *note griddata: doc-griddata, *note delaunayn:
     doc-delaunayn.

   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));
     griddata(x,y,z,xx,yy);

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


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.

 -- Function File:  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 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: doc-polyfit.

 -- Loadable Function:  fft (X)
 -- Loadable Function:  fft (X, N)
 -- Loadable Function:  fft (X, N, DIM)
     Compute the discrete Fourier transform of A 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: doc-ifft, *note fft2: doc-fft2, *note
     fftn: doc-fftn, *note fftw: doc-fftw.

   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.

 -- Loadable Function: METHOD = fftw ('planner')
 -- Loadable Function:  fftw ('planner', METHOD)
 -- Loadable Function: WISDOM = fftw ('dwisdom')
 -- Loadable Function:  fftw ('dwisdom', WISDOM)
     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 reimported as follows

          fftw ('dwisdom', WISDOM)

     If WISDOM is an empty matrix, 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.

     *See also:* *note fft: doc-fft, *note ifft: doc-ifft, *note fft2:
     doc-fft2, *note ifft2: doc-ifft2, *note fftn: doc-fftn, *note
     ifftn: doc-ifftn.

 -- Loadable Function:  ifft (X)
 -- Loadable Function:  ifft (X, N)
 -- Loadable Function:  ifft (X, N, DIM)
     Compute the inverse discrete Fourier transform of A 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: doc-fft, *note ifft2: doc-ifft2, *note
     ifftn: doc-ifftn, *note fftw: doc-fftw.

 -- Loadable Function:  fft2 (A)
 -- Loadable Function:  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:* ifft2, fft, fftn, fftw.

 -- Loadable Function:  ifft2 (A)
 -- Loadable Function:  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:* fft2, ifft, ifftn, fftw.

 -- Loadable Function:  fftn (A)
 -- Loadable Function:  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: doc-ifftn, *note fft: doc-fft, *note
     fft2: doc-fft2, *note fftw: doc-fftw.

 -- Loadable Function:  ifftn (A)
 -- Loadable Function:  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: doc-fftn, *note ifft: doc-ifft, *note
     ifft2: doc-ifft2, *note fftw: doc-fftw.

 -- Function File:  fftconv (X, Y)
 -- Function File:  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: doc-deconv, *note conv: doc-conv, *note
     conv2: doc-conv2.

 -- Function File:  fftfilt (B, X, N)
     With two arguments, `fftfilt' filters X with the FIR filter B
     using the FFT.

     Given the optional third argument, N, `fftfilt' uses the
     overlap-add method to filter X with B using an N-point FFT.

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

     *See also:* *note filter: doc-filter, *note filter2: doc-filter2.

 -- Loadable Function: y = filter (B, A, X)
 -- Loadable Function: [Y, SF] = filter (B, A, X, SI)
 -- Loadable Function: [Y, SF] = filter (B, A, X, [], DIM)
 -- Loadable Function: [Y, SF] = filter (B, A, X, SI, DIM)
     Return 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.  over the first
     non-singleton dimension of X or over DIM if supplied.  An
     equivalent form of this 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: doc-filter2, *note fftfilt:
     doc-fftfilt, *note freqz: doc-freqz.

 -- Function File: Y = filter2 (B, X)
 -- Function File: 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: doc-conv2.

 -- Function File: [H, W] = freqz (B, A, N, "whole")
     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 the fourth argument is omitted, the response is evaluated at
     frequencies between 0 and  pi.

     If N is omitted, a value of 512 is assumed.

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

     For fastest computation, N should factor into a small number of
     small primes.

 -- Function File: H = freqz (B, A, W)
     Evaluate the response at the specific frequencies in the vector W.
     The values for W are measured in radians.

 -- Function File: [...] = 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.

 -- Function File:  freqz (...)
     Plot the pass band, stop band and phase response of H rather than
     returning them.

 -- Function File:  freqz_plot (W, H)
     Plot the pass band, stop band and phase response of H.

 -- Function File:  sinc (X)
     Return  sin(pi*x)/(pi*x).

 -- Function File: B = unwrap (X)
 -- Function File: B = unwrap (X, TOL)
 -- Function File: B = unwrap (X, TOL, DIM)
     Unwrap radian phases by adding 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.

 -- Function File: [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.

 -- Function File:  arch_rnd (A, B, T)
     Simulate an ARCH sequence of length T with AR coefficients B and
     CH coefficients A.  I.e., 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

 -- Function File: [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.

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

          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.

 -- Function File:  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.  I.e., 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.

 -- Function File:  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'.

 -- Function File:  blackman (M)
     Return the filter coefficients of a Blackman window of length M.

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

 -- Function File: [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.

 -- Function File:  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.

 -- Function File:  fftshift (X)
 -- Function File:  fftshift (X, DIM)
     Perform a shift of the vector X, for use with the `fft' and `ifft'
     functions, in order the 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)*df 0 (1:floor((N-1)/2))*df ]

     where df = 1 / 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.

 -- Function File:  ifftshift (X)
 -- Function File:  ifftshift (X, DIM)
     Undo the action of the `fftshift' function.  For even length X,
     `fftshift' is its own inverse, but odd lengths differ slightly.

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

 -- Function File:  hamming (M)
     Return the filter coefficients of a Hamming window of length M.

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

 -- Function File:  hanning (M)
     Return the filter coefficients of a Hanning window of length M.

     For a definition of this window type, see e.g., A. V. Oppenheim &
     R. W. Schafer, `Discrete-Time Signal Processing'.

 -- Function File:  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
     single column.

 -- Function File: PP = pchip (X, Y)
 -- Function File: 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: doc-spline, *note ppval: doc-ppval,
     *note mkpp: doc-mkpp, *note unmkpp: doc-unmkpp.

 -- Function File: [Pxx, W] = periodogram (X)
     For a data matrix X from a sample of size N, return the
     periodogram.  The angular frequency is returned in W.

     [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 (X,win,nfft,Fs,"range").

        * x: data; if real-valued a one-sided spectrum is estimated, if
          complex-valued or range indicates "twosided", the full
          spectrum is estimated.

        * win: weight data with window, x.*win is used for further
          computation, if window is empty, a rectangular window is used.

        * nfft: number of frequency bins, default max(256,
          2.^ceil(log2(length(x)))).

        * Fs: sampling rate, default 1.

        * range: "onesided" computes spectrum from [0..nfft/2+1].
          "twosided" computes spectrum from [0..nfft-1].  These strings
          can appear at any position in the list input arguments after
          window.

        * Pxx: one-, or two-sided power spectrum.

        * w: angular frequency [0..2*pi) (two-sided) or [0..pi]
          one-sided.

        * f: frequency [0..Fs) (two-sided) or [0..Fs/2] one-sided.

 -- Function File:  rectangle_lw (N, B)
     Rectangular lag window.  Subfunction used for spectral density
     estimation.

 -- Function File:  rectangle_sw (N, B)
     Rectangular spectral window.  Subfunction used for spectral density
     estimation.

 -- Function File:  sinetone (FREQ, RATE, SEC, AMPL)
     Return a sinetone of frequency FREQ with length of SEC seconds at
     sampling rate RATE and with amplitude AMPL.  The arguments FREQ
     and AMPL may be vectors of common size.

     Defaults are RATE = 8000, SEC = 1 and AMPL = 64.

 -- Function File:  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.

 -- Function File:  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_sw'.

     If WIN is omitted, the triangle window is used.  If B is omitted,
     `1 / sqrt (length (X))' is used.

 -- Function File:  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.

 -- Function File:  spencer (X)
     Return Spencer's 15 point moving average of each column of X.

 -- Function File: [Y, C] = stft (X, WIN_SIZE, INC, NUM_COEF, WIN_TYPE)
     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.

     If not all arguments are specified, the following defaults are
     used: 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.

 -- Function File:  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 , ...)

 -- Function File:  triangle_lw (N, B)
     Triangular lag window.  Subfunction used for spectral density
     estimation.

 -- Function File:  triangle_sw (N, B)
     Triangular spectral window.  Subfunction used for spectral density
     estimation.

 -- Function File: [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 basically is 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.  This is done using the `imread' function, which uses the
`GraphicsMagick' library for reading.  This means a vast number of image
formats is supported.  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 ("my_output_image.img", J);

 -- Function File: [IMG, MAP, ALPHA] = imread (FILENAME)
     Read images from various file formats.

     The size and numeric class of the output depends on the format of
     the image.  A color image is returned as an MxNx3 matrix.
     Gray-level and black-and-white images are of size MxN.  The color
     depth of the image determines the numeric class of the output:
     "uint8" or "uint16" for gray and color, and "logical" for black
     and white.

     *See also:* *note imwrite: doc-imwrite, *note imfinfo: doc-imfinfo.

 -- Function File:  imwrite (IMG, FILENAME)
 -- Function File:  imwrite (IMG, FILENAME, FMT)
 -- Function File:  imwrite (IMG, FILENAME, FMT, P1, V1, ...)
 -- Function File:  imwrite (IMG, MAP, FILENAME, ...)
     Write images in various file formats.

     If FMT is not supplied, the file extension of FILENAME is used to
     determine the format.

     The parameter-value pairs (P1, V1, ...) are optional.  Currently
     the following options are supported for JPEG images:

    `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.

     *Supported Formats*
     Extension              Format
     -------------------------------------------------------------------- 
     bmp                    Windows Bitmap
     gif                    Graphics Interchange Format
     jpg and jpeg           Joint Photographic Experts Group
     pbm                    Portable Bitmap
     pcx                    
     pgm                    Portable Graymap
     png                    Portable Network Graphics
     pnm                    Portable Anymap
     ppm                    Portable Pixmap
     ras                    Sun Raster
     tif and tiff           Tagged Image File Format
     xwd                    X11 Dump

     *Unsupported Formats*
     Extension              Format
     -------------------------------------------------------------------- 
     hdf                    Hierarchical Data Format V4
     jp2 and jpx            Joint Photographic Experts Group 2000

     *See also:* *note imread: doc-imread, *note imfinfo: doc-imfinfo.

 -- Built-in Function: VAL = IMAGE_PATH ()
 -- Built-in Function: OLD_VAL = IMAGE_PATH (NEW_VAL)
 -- Built-in Function:  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.

   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.

 -- Function File: INFO = imfinfo (FILENAME)
 -- Function File: INFO = imfinfo (URL)
     Read image information from a file.

     `imfinfo' returns a structure containing information about the
     image stored in the file FILENAME.  The output structure contains
     the following fields.

    `Filename'
          The full name of the image file.

    `FileSize'
          Number of bytes of the image on disk

    `FileModDate'
          Date of last modification to the file.

    `Height'
          Image height in pixels.

    `Width'
          Image Width in pixels.

    `BitDepth'
          Number of bits per channel per pixel.

    `Format'
          Image format (e.g., `"jpeg"').

    `LongFormat'
          Long form image format description.

    `XResolution'
          X resolution of the image.

    `YResolution'
          Y resolution of the image.

    `TotalColors'
          Number of unique colors in the image.

    `TileName'
          Tile name.

    `AnimationDelay'
          Time in 1/100ths of a second (0 to 65535) which must expire
          before displaying the next image in an animated sequence.

    `AnimationIterations'
          Number of iterations to loop an animation (e.g., Netscape
          loop extension) for.

    `ByteOrder'
          Endian option for formats that support it.  Is either
          `"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.

    `Matte'
          `true' if the image has transparency.

    `ModulusDepth'
          Image modulus depth (minimum number of bits required to
          support red/green/blue components without loss of accuracy).

    `Quality'
          JPEG/MIFF/PNG compression level.

    `QuantizeColors'
          Preferred number of colors in the image.

    `ResolutionUnits'
          Units of image resolution.  Is either `"pixels per inch"',
          `"pixels per centimeter"', or `"undefined"'.

    `ColorType'
          Image type.  Is either `"grayscale"', `"indexed"',
          `"truecolor"', or `"undefined"'.

    `View'
          FlashPix viewing parameters.

     *See also:* *note imread: doc-imread, *note imwrite: doc-imwrite.


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.

 -- Function File:  imshow (IM)
 -- Function File:  imshow (IM, LIMITS)
 -- Function File:  imshow (IM, MAP)
 -- Function File:  imshow (RGB, ...)
 -- Function File:  imshow (FILENAME)
 -- Function File:  imshow (..., STRING_PARAM1, VALUE1, ...)
 -- Function File: H = imshow (...)
     Display the image IM, where IM can be a 2-dimensional (gray-scale
     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 file name 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.

     The optional return value H is a graphics handle to the image.

     *See also:* *note image: doc-image, *note imagesc: doc-imagesc,
     *note colormap: doc-colormap, *note gray2ind: doc-gray2ind, *note
     rgb2ind: doc-rgb2ind.

 -- Function File:  image (IMG)
 -- Function File:  image (X, Y, IMG)
 -- Function File: H = image (...)
     Display a matrix as a color image.  The elements of IMG are indices
     into the current colormap, and the colormap will be scaled so that
     the extremes of IMG are mapped to the extremes of the colormap.

     The axis values corresponding to the matrix elements are specified
     in X and Y.  If you're not using gnuplot 4.2 or later, these
     variables are ignored.

     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,1)'.

     The optional return value H is a graphics handle to the image.

     *See also:* *note imshow: doc-imshow, *note imagesc: doc-imagesc,
     *note colormap: doc-colormap.

 -- Function File:  imagesc (A)
 -- Function File:  imagesc (X, Y, A)
 -- Function File:  imagesc (..., LIMITS)
 -- Function File:  imagesc (H, ...)
 -- Function File: H = imagesc (...)
     Display a scaled version of the matrix A as a color image.  The
     colormap is scaled so that the entries of the matrix occupy the
     entire colormap.  If LIMITS = [LO, HI] are given, then that range
     is set to the 'clim' of the current axes.

     The axis values corresponding to the matrix elements are specified
     in X and Y, either as pairs giving the minimum and maximum values
     for the respective axes, or as values for each row and column of
     the matrix A.

     The optional return value H is a graphics handle to the image.

     *See also:* *note image: doc-image, *note imshow: doc-imshow,
     *note caxis: doc-caxis.


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, gray-scale
images, RGB images, binary images, and indexed images.  A gray-scale
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 gray-scale 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.

 -- Function File: [IMG, MAP] = gray2ind (I, N)
     Convert a gray scale intensity image to an Octave indexed image.
     The indexed image will consist of N different intensity values.
     If not given N will default to 64.

 -- Function File:  ind2gray (X, MAP)
     Convert an Octave indexed image to a gray scale intensity image.
     If MAP is omitted, the current colormap is used to determine the
     intensities.

     *See also:* *note gray2ind: doc-gray2ind, *note rgb2ntsc:
     doc-rgb2ntsc, *note image: doc-image, *note colormap: doc-colormap.

 -- Function File: [X, MAP] = rgb2ind (RGB)
 -- Function File: [X, MAP] = rgb2ind (R, G, B)
     Convert an RGB image to an Octave indexed image.

     *See also:* *note ind2rgb: doc-ind2rgb, *note rgb2ntsc:
     doc-rgb2ntsc.

 -- Function File: RGB = ind2rgb (X, MAP)
 -- Function File: [R, R, R] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.
     If the colormap doesn't contain enough colors, pad it with the
     last color in the map.  If MAP is omitted, the current colormap is
     used for the conversion.

     *See also:* *note rgb2ind: doc-rgb2ind, *note image: doc-image,
     *note imshow: doc-imshow, *note ind2gray: doc-ind2gray, *note
     gray2ind: doc-gray2ind.

 -- Function File:  colormap (MAP)
 -- Function File:  colormap ("default")
     Set the current colormap.

     `colormap (MAP)' sets the current colormap to MAP.  The color map
     should be an N row by 3 column matrix.  The columns contain red,
     green, and blue intensities respectively.  All entries should be
     between 0 and 1 inclusive.  The new colormap is returned.

     `colormap ("default")' restores the default colormap (the `jet'
     map with 64 entries).  The default colormap is returned.

     With no arguments, `colormap' returns the current color map.

     *See also:* *note jet: doc-jet.

 -- Function File: MAP = autumn ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = bone ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = cool ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = copper ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = flag ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = gray ()
 -- Function File: 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.

 -- Function File: MAP = hot ()
 -- Function File: 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: doc-colormap.

 -- Function File:  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.  It is
     obtained by linearly varying the hue through all possible values
     while keeping constant maximum saturation and value and is
     equivalent to `hsv2rgb ([linspace(0,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: doc-colormap.

 -- Function File: MAP = jet ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = ocean ()
 -- Function File: 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.

 -- Function File: MAP = pink ()
 -- Function File: MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.  It 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: doc-colormap.

 -- Function File: MAP = prism ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = rainbow ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = spring ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = summer ()
 -- Function File: 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: doc-colormap.

 -- Function File: MAP = white ()
 -- Function File: MAP = white (N)
     Create color colormap.  This colormap is completely white.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = winter ()
 -- Function File: 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: doc-colormap.

 -- Function File:  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 instead.

     *See also:* *note colormap: doc-colormap.

   An additional colormap is `gmap40'.  This code map contains only
colors with integer values of the red, green and blue components.  This
is a workaround for a limitation of gnuplot 4.0, that does not allow
the color of line or patch objects to be set, and so `gmap40' is useful
for gnuplot 4.0 users, and in particular in conjunction with the BAR,
BARH or CONTOUR functions.

 -- Function File: MAP = gmap40 ()
 -- Function File: MAP = gmap40 (N)
     Create color colormap.  The colormap consists of red, green, blue,
     yellow, magenta and cyan.  This colormap is specifically designed
     for users of gnuplot 4.0 where these 6 colors are the allowable
     ones for patch objects.  The argument N must be a scalar.  If
     unspecified, a length of 6 is assumed.  Larger values of N result
     in a repetition of the above colors.

     *See also:* *note colormap: doc-colormap.

   The following three functions modify the existing colormap rather
than replace it.

 -- Function File: MAP_OUT = brighten (MAP, BETA)
 -- Function File: MAP_OUT = brighten (H, BETA)
 -- Function File: MAP_OUT = brighten (BETA)
     Darken or brighten the given 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.

     Should the resulting colormap MAP_OUT not be assigned, it will be
     written to the current colormap.

     The argument BETA should be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the colormap.

     *See also:* *note colormap: doc-colormap.

 -- Function File:  spinmap (T, INC)
     Cycle the colormap for T seconds with an increment of INC.  Both
     parameters are optional.  The default cycle time is 5 seconds and
     the default increment is 2.

     A higher value of INC causes a faster cycle through the colormap.

     *See also:* *note gca: doc-gca, *note colorbar: doc-colorbar.

 -- Function File:  whitebg ()
 -- Function File:  whitebg (COLOR)
 -- Function File:  whitebg ("none")
 -- Function File:  whitebg (FIG)
 -- Function File:  whitebg (FIG, COLOR)
 -- Function File:  whitebg (FIG, "none")
     Invert the colors in the current color scheme.  The root
     properties are also inverted such that all subsequent plot use the
     new color scheme.

     If defined, FIG is the handle to the figure to be inverted.  In
     this case only the specified figure has its color properties
     changed.

     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 default
     colors.

     *See also:* *note reset: doc-reset.


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 NTSC and HSV
and vice versa.

 -- Function File: HSV_MAP = rgb2hsv (RGB)
     Transform a colormap or image from the RGB space to the HSV space.

     A color in the RGB space consists of the red, green and blue
     intensities.

     In the HSV space each color is represented by their hue, saturation
     and value (brightness).  Value gives the amount of light in the
     color.  Hue describes the dominant wavelength.  Saturation is the
     amount of hue mixed into the color.

     *See also:* *note hsv2rgb: doc-hsv2rgb.

 -- Function File: RGB_MAP = hsv2rgb (HSV_MAP)
     Transform a colormap or image from the HSV space to the RGB space.

     *See also:* *note rgb2hsv: doc-rgb2hsv.

 -- Function File:  rgb2ntsc (RGB)
     Transform a colormap or image from RGB to NTSC.

     *See also:* *note ntsc2rgb: doc-ntsc2rgb.

 -- Function File:  ntsc2rgb (YIQ)
     Transform a colormap or image from NTSC to RGB.

     *See also:* *note rgb2ntsc: doc-rgb2ntsc.


File: octave.info,  Node: Audio Processing,  Next: Object Oriented Programming,  Prev: Image Processing,  Up: Top

33 Audio 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'.

 -- Function File:  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: doc-mu2lin, *note loadaudio:
     doc-loadaudio, *note saveaudio: doc-saveaudio.

 -- Function File:  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: doc-lin2mu, *note loadaudio:
     doc-loadaudio, *note saveaudio: doc-saveaudio.

 -- Function File:  loadaudio (NAME, EXT, BPS)
     Load audio data from the file `NAME.EXT' into the vector X.

     The extension EXT determines how the data in the audio file is
     interpreted; the extensions `lin' (default) and `raw' correspond
     to linear, the extensions `au', `mu', or `snd' to mu-law encoding.

     The argument BPS can be either 8 (default) or 16, and specifies
     the number of bits per sample used in the audio file.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note saveaudio: doc-saveaudio, *note playaudio: doc-playaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

 -- Function File:  saveaudio (NAME, X, EXT, BPS)
     Save a vector X of audio data to the file `NAME.EXT'.  The
     optional parameters EXT and BPS determine the encoding and the
     number of bits per sample used in the audio file (see
     `loadaudio'); defaults are `lin' and 8, respectively.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note playaudio: doc-playaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

   The following functions for audio I/O require special A/D hardware
and operating system support.  It is assumed that audio data in linear
encoding can be played and recorded by reading from and writing to
`/dev/dsp', and that similarly `/dev/audio' is used for mu-law
encoding.  These file names are system-dependent.  Improvements so that
these functions will work without modification on a wide variety of
hardware are welcome.

 -- Function File:  playaudio (NAME, EXT)
 -- Function File:  playaudio (X)
     Play the audio file `NAME.EXT' or the audio data stored in the
     vector X.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note saveaudio: doc-saveaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

 -- Function File:  record (SEC, SAMPLING_RATE)
     Record SEC seconds of audio input into the vector X.  The default
     value for SAMPLING_RATE is 8000 samples per second, or 8kHz.  The
     program waits until the user types <RET> and then immediately
     starts to record.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note saveaudio: doc-saveaudio,
     *note playaudio: doc-playaudio, *note setaudio: doc-setaudio.

 -- Function File:  setaudio ()
 -- Function File:  setaudio (W_TYPE)
 -- Function File:  setaudio (W_TYPE, VALUE)
     Execute the shell command `mixer', possibly with optional
     arguments W_TYPE and VALUE.

 -- Function File: Y = wavread (FILENAME)
     Load the RIFF/WAVE sound file FILENAME, and return the samples in
     vector Y.  If the file contains multichannel data, then Y is a
     matrix with the channels represented as columns.

 -- Function File: [Y, FS, BPS] = wavread (FILENAME)
     Additionally return the sample rate (FS) in Hz and the number of
     bits per sample (BPS).

 -- Function File: [...] = wavread (FILENAME, N)
     Read only the first N samples from each channel.

 -- Function File: [...] = wavread (FILENAME, N1 N2)
     Read only samples N1 through N2 from each channel.

 -- Function File: [SAMPLES, CHANNELS] = wavread (FILENAME, "size")
     Return the number of samples (N) and channels (CH) instead of the
     audio data.

     *See also:* *note wavwrite: doc-wavwrite.

 -- Function File:  wavwrite (Y, FILENAME)
 -- Function File:  wavwrite (Y, FS, FILENAME)
 -- Function File:  wavwrite (Y, FS, BPS, FILENAME)
     Write Y to the canonical RIFF/WAVE sound file FILENAME with sample
     rate FS and bits per sample BPS.  The default sample rate is 8000
     Hz with 16-bits per sample.  Each column of the data represents a
     separate channel.

     *See also:* *note wavread: doc-wavread.


File: octave.info,  Node: Object Oriented Programming,  Next: GUI Development,  Prev: Audio Processing,  Up: Top

34 Object Oriented Programming
******************************

Octave includes the capability to include user classes, including the
features of operator and function overloading.  Equally a user class
can be used to encapsulate certain properties of the class so that they
cannot be altered accidentally and can be set up to address the issue
of class precedence in mixed class operations.

   This chapter discussions the means of constructing a user class with
the example of a polynomial class, how to query and set the properties
of this class, together with the means to overload operators and
functions.

* Menu:

* Creating a Class::
* Manipulating Classes::
* Indexing Objects::
* Overloading Objects::
* Inheritance and Aggregation::


File: octave.info,  Node: Creating a Class,  Next: Manipulating Classes,  Up: Object Oriented Programming

34.1 Creating a Class
=====================

We use in the following text a polynomial class to demonstrate the use
of object oriented programming within Octave.  This class was chosen as
it is simple, and so doesn't distract unnecessarily from the discussion
of the programming features of Octave.  However, even still a small
understand of the polynomial class itself is necessary to fully grasp
the techniques described.

   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];

   We therefore now have sufficient information about the requirements
of the class constructor for our polynomial class to write it.  All
object oriented classes in Octave, must be contained with a directory
taking the name of the class, prepended with the @ symbol.  For
example, with our polynomial class, we would place the methods defining
the class in the @polynomial directory.

   The constructor of the class, must have the name of the class itself
and so in our example the constructor with have the name
`@polynomial/polynomial.m'.  Also ideally when the constructor is
called with no arguments to should return a value object.  So for
example our polynomial might look like

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} 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 == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
     endfunction

   Note that the return value of the constructor must be the output of
the `class' function called with the first argument being a structure
and the second argument being the class name.  An example of the call
to this constructor function is then

     p = polynomial ([1, 0, 1]);

   Note that methods of a class can be documented.  The help for the
constructor itself can be obtained with the constructor name, that is
for the polynomial constructor `help polynomial' will return the help
string.  Also the help can be obtained by restricting the search for
the help to a particular class, for example `help
@polynomial/polynomial'.  This second method is the only means of
getting help for the overloaded methods and functions of the class.

   The same is true for other Octave functions that take a function name
as an argument.  For example `type @polynomial/display' will print the
code of the display method of the polynomial class to the screen, and
`dbstop @polynomial/display' will set a breakpoint at the first
executable line of the display method of the polynomial class.

   To check where a variable is 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

 -- Built-in Function:  isobject (X)
     Return true if X is a class object.

     *See also:* *note class: doc-class, *note typeinfo: doc-typeinfo,
     *note isa: doc-isa, *note ismethod: doc-ismethod.

The available methods of a class can be displayed with the `methods'
function.

 -- Built-in Function:  methods (X)
 -- Built-in Function:  methods ("classname")
     Return a cell array containing the names of the methods for the
     object X or the named class.

To inquire whether a particular method is available to a user class, the
`ismethod' function can be used.

 -- Built-in Function:  ismethod (X, METHOD)
     Return true if X is a class object and the string METHOD is a
     method of this class.

     *See also:* *note isobject: doc-isobject.

For example:

     p = polynomial ([1, 0, 1]);
     ismethod (p, "roots")
       => 1


File: octave.info,  Node: Manipulating Classes,  Next: Indexing Objects,  Prev: Creating a Class,  Up: Object Oriented Programming

34.2 Manipulating Classes
=========================

There are a number of basic classes methods that can be defined to allow
the contents of the classes to be queried and set.  The most basic of
these is the `display' method.  The `display' method is used by Octave
when displaying a class on the screen, due to an expression that is not
terminated with a semicolon.  If this method is not defined, then
Octave will printed nothing when displaying the contents of a class.

 -- Function File:  display (A)
     Display the contents of an object.  If A is an object of the class
     "myclass", then `display' is called in a case like

          myclass (...)

     where Octave is required to display the contents of a variable of
     the type "myclass".

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.

An example of a display method for the polynomial class might be

     function display (p)
       a = p.poly;
       first = true;
       fprintf("%s =", inputname(1));
       for i = 1 : length (a);
         if (a(i) != 0)
           if (first)
             first = false;
           elseif (a(i) > 0)
             fprintf (" +");
           endif
           if (a(i) < 0)
             fprintf (" -");
           endif
           if (i == 1)
             fprintf (" %g", abs (a(i)));
           elseif (abs(a(i)) != 1)
             fprintf (" %g *", abs (a(i)));
           endif
           if (i > 1)
             fprintf (" X");
           endif
           if (i > 2)
             fprintf (" ^ %d", i - 1);
           endif
         endif
       endfor
       if (first)
         fprintf(" 0");
       endif
       fprintf("\n");
     endfunction

Note that in the display method, it makes sense to start the method
with the line `fprintf("%s =", inputname(1))' to be consistent with the
rest of Octave and print the variable name to be displayed when
displaying the class.

   To be consistent with the Octave graphic handle classes, a class
should also define the `get' and `set' methods.  The `get' method
should accept one or two arguments, and given one argument of the
appropriate class it should return a structure with all of the
properties of the class.  For example:

     function s = get (p, f)
       if (nargin == 1)
         s.poly = p.poly;
       elseif (nargin == 2)
         if (ischar (f))
           switch (f)
             case "poly"
               s = p.poly;
             otherwise
               error ("get: invalid property %s", f);
           endswitch
         else
           error ("get: expecting the property to be a string");
         endif
       else
         print_usage ();
       endif
     endfunction

Similarly, the `set' method should taken as its first argument an
object to modify, and then take property/value pairs to be modified.

     function s = set (p, varargin)
       s = p;
       if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
         error ("set: expecting property/value pairs");
       endif
       while (length (varargin) > 1)
         prop = varargin{1};
         val = varargin{2};
         varargin(1:2) = [];
         if (ischar (prop) && strcmp (prop, "poly"))
           if (isvector (val) && isreal (val))
             s.poly = val(:).';
           else
             error ("set: expecting the value to be a real vector");
           endif
         else
           error ("set: invalid property of polynomial class");
         endif
       endwhile
     endfunction

Note that as Octave does not implement pass by reference, than the
modified object is the return value of the `set' method and it must be
called like

     p = set (p, "a", [1, 0, 0, 0, 1]);

Also the `set' method makes use of the `subsasgn' method of the class,
and this method must be defined.  The `subsasgn' method is discussed in
the next section.

   Finally, user classes can be considered as a special type of a
structure, and so 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 either contain a field
that it makes no 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

 -- Function File: 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: doc-loadobj, *note class: doc-class.

`saveobj' is called just prior to saving the class to a file.  Likely,
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.

 -- Function File: 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: doc-saveobj, *note class: doc-class.


File: octave.info,  Node: Indexing Objects,  Next: Overloading Objects,  Prev: Manipulating Classes,  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, either like `A (IDX)' or like
`A {IDX}', or even like `A (IDX).FIELD'.  However, it is up to the user
to decide what this indexing actually means.  In the case of our
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.

 -- Built-in Function:  subsref (VAL, IDX)
     Perform the subscripted element selection operation according to
     the subscript specified by IDX.

     The subscript IDX is expected to 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 two first 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: doc-subsasgn, *note substruct:
     doc-substruct.

   For example we might decide that indexing with "()" evaluates the
polynomial and indexing with "{}" returns the N-th coefficient (of N-th
power).  In this case the `subsref' method of our polynomial class
might look like

     function b = subsref (a, s)
       if (isempty (s))
         error ("polynomial: missing index");
       endif
       switch (s(1).type)
         case "()"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             b = polyval (fliplr (a.poly), ind{1});
           endif
         case "{}"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             if (isnumeric (ind{1}))
               b = a.poly(ind{1}+1);
             else
               b = a.poly(ind{1});
             endif
           endif
         case "."
           fld = s.subs;
           if (strcmp (fld, "poly"))
             b = a.poly;
           else
             error ("@polynomial/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("invalid subscript type");
       endswitch
       if (numel (s) > 1)
         b = subsref (b, s(2:end));
       endif
     endfunction

   The equivalent functionality for subscripted assignments uses the
`subsasgn' method.

 -- Built-in Function:  subsasgn (VAL, IDX, RHS)
     Perform the subscripted assignment operation according to the
     subscript specified by IDX.

     The subscript IDX is expected to 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: doc-subsref, *note substruct:
     doc-substruct.

 -- Built-in Function: VAL = optimize_subsasgn_calls ()
 -- Built-in Function: OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- Built-in Function:  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 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.

   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 the user needs to define the `end' method for the
class.  For example, the `end' method for our 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.  It can then be used as
follows:

     p = polynomial([1,2,3,4]);
     p(end-1)
       => 3

   Objects can also be used as the index in a subscripted expression
themselves and this is controlled with the `subsindex' function.

 -- Function File: IDX = subsindex (A)
     Convert an object to an index vector.  When A 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

          function b = myclass (a)
            b = class (struct ("a", a), "myclass");
          endfunction

     then the `subsindex' function

          function idx = subsindex (a)
            idx = double (a.a) - 1.0;
          endfunction

     can then be used as follows

          a = myclass (1:4);
          b = 1:10;
          b(a)
          => 1  2  3  4

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.

   Finally, objects can equally be used like ranges, using the `colon'
method

 -- Function File: R = colon (A, B)
 -- Function File: R = colon (A, B, C)
     Method of a class to construct a range with the `:' operator.  For
     example:

          a = myclass (...);
          b = myclass (...);
          c = a : b

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.


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 a
call to subsasgn:

       ss = substruct ("()",{1});
       x = subsasgn (x, ss, 1);

and 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, i.e., degrades a constant-time operation 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 direct
subsasgn call as shown above), i.e.

       x(1) = 1;

   AND if the subsasgn method is declared with identical input and
output argument, like 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' in the caller's scope
will exist, it is _solely_ the callee's responsibility to not leave `x'
in an invalid state if an error occurs throughout 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 built-in variable `optimize_subsasgn_calls' is
provided to control it.  It is on by default.  Another option to avoid
the effect 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 allows an object specific
version of this function to be called as needed.  A pertinent example
for our polynomial class might be to overload the `polyval' function
like

     function [y, dy] = polyval (p, varargin)
       if (nargout == 2)
         [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 for an overloaded function for
our 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, p(x), varargin{:});
       else
         plot(x, 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 to be overloaded are the
class conversion functions such as `double'.  Overloading these
functions allows the `cast' function to work with the user class and
can aid in the use of methods of other classes with the user class.  An
example `double' function for our polynomial class might look like.

     function b = double (a)
       b = a.poly;
     endfunction


File: octave.info,  Node: Operator Overloading,  Next: Precedence of Objects,  Prev: Function Overloading,  Up: Overloading Objects

34.4.2 Operator Overloading
---------------------------

        Operation      Method         Description                   
---------------------------------------------------------------------------- 
        a + b          plus (a, b)    Binary addition               
        a - b          minus (a, b)   Binary subtraction operator   
        + a            uplus (a)      Unary addition operator       
        - a            uminus (a)     Unary subtraction operator    
        a .* b         times (a, b)   Element-wise multiplication   
                                      operator                      
        a * b          mtimes (a, b)  Matrix multiplication         
                                      operator                      
        a ./ b         rdivide (a,    Element-wise right division   
                       b)             operator                      
        a / b          mrdivide (a,   Matrix right division         
                       b)             operator                      
        a .\ b         ldivide (a,    Element-wise left division    
                       b)             operator                      
        a \ b          mldivide (a,   Matrix left division          
                       b)             operator                      
        a .^ b         power (a, b)   Element-wise power operator   
        a ^ b          mpower (a, b)  Matrix power operator         
        a < b          lt (a, b)      Less than operator            
        a <= b         le (a, b)      Less than or equal to         
                                      operator                      
        a > b          gt (a, b)      Greater than operator         
        a >= b         ge (a, b)      Greater than or equal to      
                                      operator                      
        a == b         eq (a, b)      Equal to operator             
        a != b         ne (a, b)      Not equal to operator         
        a & b          and (a, b)     Logical and operator          
        a | b          or (a, b)      Logical or operator           
        ! b            not (a)        Logical not operator          
        a'             ctranspose     Complex conjugate transpose   
                       (a)            operator                      
        a.'            transpose (a)  Transpose operator            
        a : b          colon (a, b)   Two element range operator    
        a : b : c      colon (a, b,   Three element range operator  
                       c)                                           
        [a, b]         horzcat (a,    Horizontal concatenation      
                       b)             operator                      
        [a; b]         vertcat (a,    Vertical concatenation        
                       b)             operator                      
        a(s_1, ...,    subsref (a,    Subscripted reference         
        s_n)           s)                                           
        a(s_1, ...,    subsasgn (a,   Subscripted assignment        
        s_n) = b       s, b)                                        
        b (a)          subsindex (a)  Convert to zero-based index   
        "display"      display (a)    Commandline display function  

Table 34.1: Available overloaded operators and their corresponding
class method

   An example `mtimes' method for our polynomial class might look like

     function y = mtimes (a, b)
       y = 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 so the case
can easily arise that these functions are called with objects of
different classes.  It is therefore necessary to determine the
precedence of which method of 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

 -- Built-in Function:  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.

 -- Built-in Function:  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.

   For example with our 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 we like to ensure that the return type of
the above is of the type "polynomial" and so we use the `superiorto'
function in the class constructor.  In particular our polynomial class
constructor would be modified to be

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} 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 == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
       superiorto ("double");
     endfunction

   Note that user classes always have higher precedence than built-in
Octave types.  So in fact marking our polynomial class higher than the
"double" class is in fact not necessary.


File: octave.info,  Node: Inheritance and Aggregation,  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 struct 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 struct.  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 easily demonstrated by example.  Suppose the programmer needs
an FIR filter, i.e., a filter with a numerator polynomial but a unity
denominator polynomial.  In traditional octave programming, this would
be performed as follows.

     octave:1> x = [some data vector];
     octave:2> n = [some coefficient vector];
     octave:3> y = filter (n, 1, x);

   The equivalent class could be implemented in a class directory
@FIRfilter that is on the octave path.  The constructor is a file
FIRfilter.m in the class directory.

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn

     function f = FIRfilter (p)

       f.polynomial = [];
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (nargin == 1)
         if (!isa (p, "polynomial"))
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter", p);
     endfunction

   As before, the leading comments provide command-line documentation
for the class constructor.  This constructor is very similar to the
polynomial class constructor, except that we pass a polynomial object
as the third argument to the class function, telling octave that the
FIRfilter class will be derived from the polynomial class.  Our FIR
filter does not have any data fields, but we must provide a struct to
the `class' function.  The `class' function will add an element named
polynomial to the object struct, so we simply add a dummy element named
polynomial as the first line of the constructor.  This dummy element
will be overwritten by the class function.

   Note further that all our examples provide for the case in which no
arguments are supplied.  This is important since octave will call the
constructor with no arguments when loading objects from save files to
determine the inheritance structure.

   A class may be a child of more than one class (see the documentation
for the `class' function), 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.

   As before, we need a `display' method.  A simple example might be

     function display (f)

       display(f.polynomial);

     endfunction

   Note that we have used the polynomial field of the struct to display
the filter coefficients.

   Once we have the class constructor and display method, we may create
an object by calling the class constructor.  We may also check the
class type and examine the underlying structure.

     octave:1> f=FIRfilter(polynomial([1 1 1]/3))
     f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * 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 =
     {
     polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     }

   We only need to define a method to actually process data with our
filter and our class is usable.  It is also useful to provide a means
of changing the data stored in the class.  Since the fields in the
underlying struct are private by default, we could provide a mechanism
to access the fields.  The `subsref' method may be used for both.

     function out = subsref (f, x)
       switch x.type
         case "()"
           n = f.polynomial;
           out = filter(n.poly, 1, x.subs{1});
         case "."
           fld = x.subs;
           if (strcmp (fld, "polynomial"))
             out = f.polynomial;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         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.333333 + 0.333333 * X + 0.333333 * X ^ 2

   In order to change the contents of the object, we need to define a
`subsasgn' method.  For example, we may make the polynomial field
publicly writable.

     function out = subsasgn (f, index, val)
       switch (index.type)
         case "."
           fld = index.subs;
           if (strcmp (fld, "polynomial"))
             out = f;
             out.polynomial = val;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("FIRfilter/subsagn: Invalid index type")
       endswitch
     endfunction

   So that

     octave:6> f=FIRfilter();
     octave:7> 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 and FIRfilter object may be used any place that a
polynomial may be used.  This is not a normal use of a filter, so that
aggregation may be a more sensible design approach.  In this case, the
polynomial is simply a field in the class structure.  A class
constructor for this case might be

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn

     function f = FIRfilter (p)

       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       elseif (nargin == 1)
         if (isa (p, "polynomial"))
           f.polynomial = p;
         else
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter");
     endfunction

   For our example, the remaining class methods remain unchanged.


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 limited features for constructing graphical interfaces
for interacting with users.

   The GUI elements available are I/O dialogs and a progress bar.  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.

   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::
* GUI Utility Functions::
* User-Defined Preferences::


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 file name.

 -- Function File: DIRNAME = uigetdir ()
 -- Function File: DIRNAME = uigetdir (INIT_PATH)
 -- Function File: 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.

     *See also:* *note uigetfile: doc-uigetfile.

 -- Function File: [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- Function File: [...] = uigetfile (FLT)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- Function File: [...] = uigetfile (..., "Position", [PX PY])
 -- Function File: [...] = uigetfile (..., "MultiSelect", MODE)
     Open a GUI dialog for selecting a file.  It returns 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 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"})'

     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.

 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- Function File: [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 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.


File: octave.info,  Node: Progress Bar,  Next: GUI Utility Functions,  Prev: I/O Dialogs,  Up: GUI Development

35.2 Progress Bar
=================

 -- Function File: H = waitbar (FRAC)
 -- Function File: H = waitbar (FRAC, MSG)
 -- Function File: H = waitbar (..., "FigureProperty", "Value", ...)
 -- Function File:  waitbar (FRAC)
 -- Function File:  waitbar (FRAC, HWBAR)
 -- Function File:  waitbar (FRAC, HWBAR, MSG)
     Return a handle H to a new 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.  The
     appearance of the waitbar figure window can be configured by
     passing property/value 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 HWBAR of the specific waitbar to modify.


File: octave.info,  Node: GUI Utility Functions,  Next: User-Defined Preferences,  Prev: Progress Bar,  Up: GUI Development

35.3 GUI Utility Functions
==========================

These functions do not implement a GUI element but are useful when
developing programs that do.  *Warning:* The functions `uiwait',
`uiresume', and `waitfor' are only available for the FLTK tooolkit.

 -- Function File: DATA = guidata (HANDLE)
 -- Function File:  guidata (HANDLE, DATA)

 -- Function File: HDATA = guihandles (HANDLE)
 -- Function File: HDATA = guihandles

 -- Function File:  uiwait
 -- Function File:  uiwait (H)
 -- Function File:  uiwait (H, TIMEOUT)
     Suspend program execution until the figure with handle H is
     deleted or `uiresume' is called.  When no figure handle is
     specified, this function uses the current figure.

     If the figure handle is invalid or there is no current figure, this
     functions returns immediately.

     When specified, TIMEOUT defines the number of seconds to wait for
     the figure deletion or the `uiresume' call.  The timeout value
     must be at least 1. If a smaller value is specified, a warning is
     issued and a timeout value of 1 is used instead.  If a non-integer
     value is specified, it is truncated towards 0. If TIMEOUT is not
     specified, the program execution is suspended indefinitely.

     *See also:* *note uiresume: doc-uiresume, *note waitfor:
     doc-waitfor.

 -- Function File:  uiresume (H)
     Resume program execution suspended with `uiwait'.  The handle H
     must be the same as the on specified in `uiwait'.  If the handle
     is invalid or there is no `uiwait' call pending for the figure
     with handle H, this function does nothing.

     *See also:* *note uiwait: doc-uiwait.

 -- Built-in Function:  waitfor (H)
 -- Built-in Function:  waitfor (H, PROP)
 -- Built-in Function:  waitfor (H, PROP, VALUE)
 -- Built-in Function:  waitfor (..., "timeout", TIMEOUT)
     Suspend the execution of the current program until a condition is
     satisfied on the graphics handle H.  While the program is suspended
     graphics events are still being processed normally, allowing
     callbacks to modify the state of graphics objects.  This function
     is reentrant and can be called from a callback, while another
     `waitfor' call is pending at top-level.

     In the first form, program execution is suspended until the
     graphics object H is destroyed.  If the graphics handle is
     invalid, the function returns immediately.

     In the second form, execution is suspended until the graphics
     object is destroyed or the property named PROP is modified.  If
     the graphics handle is invalid or the property does not exist, the
     function returns immediately.

     In the third form, execution is suspended until the graphics
     object is destroyed or the property named PROP is set to VALUE.
     The function `isequal' is used to compare property values.  If the
     graphics handle is invalid, the property does not exist or the
     property is already set to VALUE, the function returns immediately.

     An optional timeout can be specified using the property `timeout'.
     This timeout value is the number of seconds to wait for the
     condition to be true.  TIMEOUT must be at least 1. If a smaller
     value is specified, a warning is issued and a value of 1 is used
     instead.  If the timeout value is not an integer, it is truncated
     towards 0.

     To define a condition on a property named `timeout', use the string
     `\timeout' instead.

     In all cases, typing CTRL-C stops program execution immediately.

     *See also:* *note isequal: doc-isequal.


File: octave.info,  Node: User-Defined Preferences,  Prev: GUI Utility Functions,  Up: GUI Development

35.4 User-Defined Preferences
=============================

 -- Function File:  addpref (GROUP, PREF, VAL)
     Add a preference PREF and associated value VAL to the named
     preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, VAL must be a cell array
     of values with the same size as PREF.

     *See also:* *note setpref: doc-setpref, *note getpref:
     doc-getpref, *note ispref: doc-ispref, *note rmpref: doc-rmpref.

 -- Function File:  getpref (GROUP, PREF, DEFAULT)
     Return the preference value corresponding to the named preference
     PREF in the preference group GROUP.

     The named preference group must be a character string.

     If PREF does not exist in GROUP and DEFAULT is specified, return
     DEFAULT.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding default value DEFAULT may be
     any value, or, if PREF is a cell array of strings, DEFAULT must be
     a cell array of values with the same size as PREF.

     If neither PREF nor DEFAULT are specified, return a structure of
     preferences for the preference group GROUP.

     If no arguments are specified, return a structure containing all
     groups of preferences and their values.

     *See also:* *note addpref: doc-addpref, *note setpref:
     doc-setpref, *note ispref: doc-ispref, *note rmpref: doc-rmpref.

 -- Function File:  ispref (GROUP, PREF)
     Return true if the named preference PREF exists in the preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.

     If PREF is not specified, return true if the preference group
     GROUP exists.

     *See also:* *note getpref: doc-getpref, *note addpref:
     doc-addpref, *note setpref: doc-setpref, *note rmpref: doc-rmpref.

 -- Function File:  rmpref (GROUP, PREF)
     Remove the named preference PREF from the preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.

     If PREF is not specified, remove the preference group GROUP.

     It is an error to remove a nonexistent preference or group.

     *See also:* *note addpref: doc-addpref, *note ispref: doc-ispref,
     *note setpref: doc-setpref, *note getpref: doc-getpref.

 -- Function File:  setpref (GROUP, PREF, VAL)
     Set a preference PREF to the given VAL in the named preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, VAL must be a cell array
     of values with the same size as PREF.

     If the named preference or group does not exist, it is added.

     *See also:* *note addpref: doc-addpref, *note getpref:
     doc-getpref, *note ispref: doc-ispref, *note rmpref: doc-rmpref.


File: octave.info,  Node: System Utilities,  Next: Packages,  Prev: GUI Development,  Up: Top

36 System Utilities
*******************

This chapter describes the functions that are available to allow you to
get information about what is happening outside of Octave, while it is
still running, and use this information in your program.  For example,
you can get information about environment variables, the current time,
and even start other programs from the Octave prompt.

* Menu:

* Timing Utilities::
* Filesystem Utilities::
* File Archiving Utilities::
* Networking Utilities::
* Controlling Subprocesses::
* Process ID Information::
* Environment Variables::
* Current Working Directory::
* Password Database Functions::
* Group Database Functions::
* System Information::
* Hashing Functions::


File: octave.info,  Node: Timing Utilities,  Next: Filesystem Utilities,  Up: System Utilities

36.1 Timing Utilities
=====================

Octave's core set of functions for manipulating time values are
patterned after the corresponding functions from the standard C library.
Several of these functions use a data structure for time that includes
the following elements:

`usec'
     Microseconds after the second (0-999999).

`sec'
     Seconds after the minute (0-60).  This number can be 60 to account
     for leap seconds.

`min'
     Minutes after the hour (0-59).

`hour'
     Hours since midnight (0-23).

`mday'
     Day of the month (1-31).

`mon'
     Months since January (0-11).

`year'
     Years since 1900.

`wday'
     Days since Sunday (0-6).

`yday'
     Days since January 1 (0-365).

`isdst'
     Daylight Savings Time flag.

`zone'
     Time zone.

In the descriptions of the following functions, this structure is
referred to as a TM_STRUCT.

 -- Loadable Function: SECONDS = time ()
     Return the current time as the number of seconds since the epoch.
     The epoch is referenced to 00:00:00 CUT (Coordinated Universal
     Time) 1 Jan 1970.  For example, on Monday February 17, 1997 at
     07:15:06 CUT, the value returned by `time' was 856163706.

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note gmtime:
     doc-gmtime, *note mktime: doc-mktime, *note now: doc-now, *note
     date: doc-date, *note clock: doc-clock, *note datenum:
     doc-datenum, *note datestr: doc-datestr, *note datevec:
     doc-datevec, *note calendar: doc-calendar, *note weekday:
     doc-weekday.

 -- Function File: t = now ()
     Return the current local date/time as a serial day number (see
     `datenum').

     The integral part, `floor (now)' corresponds to the number of days
     between today and Jan 1, 0000.

     The fractional part, `rem (now, 1)' corresponds to the current
     time.

     *See also:* *note clock: doc-clock, *note date: doc-date, *note
     datenum: doc-datenum.

 -- Function File:  ctime (T)
     Convert a value returned from `time' (or any other non-negative
     integer), to the local time and return a string of the same form as
     `asctime'.  The function `ctime (time)' is equivalent to `asctime
     (localtime (time))'.  For example:

          ctime (time ())
             => "Mon Feb 17 01:15:06 1997"

     *See also:* *note asctime: doc-asctime, *note time: doc-time,
     *note localtime: doc-localtime.

 -- Loadable Function: TM_STRUCT = gmtime (T)
     Given a value returned from `time', or any non-negative integer,
     return a time structure corresponding to CUT (Coordinated
     Universal Time).  For example:

          gmtime (time ())
               => {
                     usec = 0
                     sec = 6
                     min = 15
                     hour = 7
                     mday = 17
                     mon = 1
                     year = 97
                     wday = 1
                     yday = 47
                     isdst = 0
                     zone = CST
                   }

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note mktime:
     doc-mktime, *note time: doc-time, *note now: doc-now, *note date:
     doc-date, *note clock: doc-clock, *note datenum: doc-datenum,
     *note datestr: doc-datestr, *note datevec: doc-datevec, *note
     calendar: doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: TM_STRUCT = localtime (T)
     Given a value returned from `time', or any non-negative integer,
     return a time structure corresponding to the local time zone.

          localtime (time ())
               => {
                     usec = 0
                     sec = 6
                     min = 15
                     hour = 1
                     mday = 17
                     mon = 1
                     year = 97
                     wday = 1
                     yday = 47
                     isdst = 0
                     zone = CST
                   }

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: SECONDS = mktime (TM_STRUCT)
     Convert a time structure corresponding to the local time to the
     number of seconds since the epoch.  For example:

          mktime (localtime (time ()))
               => 856163706

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note gmtime:
     doc-gmtime, *note time: doc-time, *note now: doc-now, *note date:
     doc-date, *note clock: doc-clock, *note datenum: doc-datenum,
     *note datestr: doc-datestr, *note datevec: doc-datevec, *note
     calendar: doc-calendar, *note weekday: doc-weekday.

 -- Function File:  asctime (TM_STRUCT)
     Convert a time structure to a string using the following format:
     "ddd mmm mm HH:MM:SS yyyy".  For example:

          asctime (localtime (time ()))
               => "Mon Feb 17 01:15:06 1997"

     This is equivalent to `ctime (time ())'.

     *See also:* *note ctime: doc-ctime, *note localtime:
     doc-localtime, *note time: doc-time.

 -- Loadable Function:  strftime (FMT, TM_STRUCT)
     Format the time structure TM_STRUCT in a flexible way using the
     format string FMT that contains `%' substitutions similar to those
     in `printf'.  Except where noted, substituted fields have a fixed
     size; numeric fields are padded if necessary.  Padding is with
     zeros by default; for fields that display a single number, padding
     can be changed or inhibited by following the `%' with one of the
     modifiers described below.  Unknown field specifiers are copied as
     normal characters.  All other characters are copied to the output
     without change.  For example:

          strftime ("%r (%Z) %A %e %B %Y", localtime (time ()))
               => "01:15:06 AM (CST) Monday 17 February 1997"

     Octave's `strftime' function supports a superset of the ANSI C
     field specifiers.

     Literal character fields:

    `%%'
          % character.

    `%n'
          Newline character.

    `%t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

    `- (dash)'
          Do not pad the field.

    `_ (underscore)'
          Pad the field with spaces.

     Time fields:

    `%H'
          Hour (00-23).

    `%I'
          Hour (01-12).

    `%k'
          Hour (0-23).

    `%l'
          Hour (1-12).

    `%M'
          Minute (00-59).

    `%p'
          Locale's AM or PM.

    `%r'
          Time, 12-hour (hh:mm:ss [AP]M).

    `%R'
          Time, 24-hour (hh:mm).

    `%s'
          Time in seconds since 00:00:00, Jan 1, 1970 (a nonstandard
          extension).

    `%S'
          Second (00-61).

    `%T'
          Time, 24-hour (hh:mm:ss).

    `%X'
          Locale's time representation (%H:%M:%S).

    `%Z'
          Time zone (EDT), or nothing if no time zone is determinable.

     Date fields:

    `%a'
          Locale's abbreviated weekday name (Sun-Sat).

    `%A'
          Locale's full weekday name, variable length (Sunday-Saturday).

    `%b'
          Locale's abbreviated month name (Jan-Dec).

    `%B'
          Locale's full month name, variable length (January-December).

    `%c'
          Locale's date and time (Sat Nov 04 12:02:33 EST 1989).

    `%C'
          Century (00-99).

    `%d'
          Day of month (01-31).

    `%e'
          Day of month ( 1-31).

    `%D'
          Date (mm/dd/yy).

    `%h'
          Same as %b.

    `%j'
          Day of year (001-366).

    `%m'
          Month (01-12).

    `%U'
          Week number of year with Sunday as first day of week (00-53).

    `%w'
          Day of week (0-6).

    `%W'
          Week number of year with Monday as first day of week (00-53).

    `%x'
          Locale's date representation (mm/dd/yy).

    `%y'
          Last two digits of year (00-99).

    `%Y'
          Year (1970-).

     *See also:* *note strptime: doc-strptime, *note localtime:
     doc-localtime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: [TM_STRUCT, NCHARS] = strptime (STR, FMT)
     Convert the string STR to the time structure TM_STRUCT under the
     control of the format string FMT.

     If FMT fails to match, NCHARS is 0; otherwise, it is set to the
     position of last matched character plus 1. Always check for this
     unless you're absolutely sure the date string will be parsed
     correctly.

     *See also:* *note strftime: doc-strftime, *note localtime:
     doc-localtime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

   Most of the remaining functions described in this section are not
patterned after the standard C library.  Some are available for
compatibility with MATLAB and others are provided because they are
useful.

 -- Function File:  clock ()
     Return the current local date and time as a date vector.  The date
     vector contains the following fields: current year, month (1-12),
     day (1-31), hour (0-23), minute (0-59), and second (0-61).  The
     seconds field has a fractional part after the decimal point for
     extended accuracy.

     For example:

          fix (clock ())
               => [ 1993, 8, 20, 4, 56, 1 ]

     The function clock is more accurate on systems that have the
     `gettimeofday' function.

     *See also:* *note now: doc-now, *note date: doc-date, *note
     datevec: doc-datevec.

 -- Function File:  date ()
     Return the current date as a character string in the form
     DD-MMM-YYYY.

     For example:

          date ()
            => "20-Aug-1993"

     *See also:* *note now: doc-now, *note clock: doc-clock, *note
     datestr: doc-datestr, *note localtime: doc-localtime.

 -- Function File:  etime (T2, T1)
     Return the difference in seconds between two time values returned
     from `clock' (T2 - T1).  For example:

          t0 = clock ();
          # many computations later...
          elapsed_time = etime (clock (), t0);

     will set the variable `elapsed_time' to the number of seconds since
     the variable `t0' was set.

     *See also:* *note tic: doc-tic, *note toc: doc-toc, *note clock:
     doc-clock, *note cputime: doc-cputime, *note addtodate:
     doc-addtodate.

 -- Built-in Function: [TOTAL, USER, SYSTEM] = cputime ();
     Return the CPU time used by your Octave session.  The first output
     is the total time spent executing your process and is equal to the
     sum of second and third outputs, which are the number of CPU
     seconds spent executing in user mode and the number of CPU seconds
     spent executing in system mode, respectively.  If your system does
     not have a way to report CPU time usage, `cputime' returns 0 for
     each of its output values.  Note that because Octave used some CPU
     time to start, it is reasonable to check to see if `cputime' works
     by checking to see if the total CPU time used is nonzero.

 -- Function File:  is_leap_year ()
 -- Function File:  is_leap_year (YEAR)
     Return true if YEAR is a leap year and false otherwise.  If no
     year is specified, `is_leap_year' uses the current year.  For
     example:

          is_leap_year (2000)
             => 1

     *See also:* *note weekday: doc-weekday, *note eomday: doc-eomday,
     *note calendar: doc-calendar.

 -- Built-in Function:  tic ()
 -- Built-in Function:  toc ()
     Set or check a wall-clock timer.  Calling `tic' without an output
     argument sets the timer.  Subsequent calls to `toc' return the
     number of seconds since the timer was set.  For example,

          tic ();
          # many computations later...
          elapsed_time = toc ();

     will set the variable `elapsed_time' to the number of seconds since
     the most recent call to the function `tic'.

     If called with one output argument then this function returns a
     scalar of type `uint64' and the wall-clock timer is not started.

          t = tic; sleep (5); (double (tic ()) - double (t)) * 1e-6
               => 5

     Nested timing with `tic' and `toc' is not supported.  Therefore
     `toc' will always return the elapsed time from the most recent
     call to `tic'.

     If you are more interested in the CPU time that your process used,
     you should use the `cputime' function instead.  The `tic' and
     `toc' functions report the actual wall clock time that elapsed
     between the calls.  This may include time spent processing other
     jobs or doing nothing at all.  For example:

          tic (); sleep (5); toc ()
               => 5
          t = cputime (); sleep (5); cputime () - t
               => 0

     (This example also illustrates that the CPU timer may have a fairly
     coarse resolution.)

 -- Built-in Function:  pause (SECONDS)
     Suspend the execution of the program.  If invoked without any
     arguments, Octave waits until you type a character.  With a
     numeric argument, it pauses for the given number of seconds.  For
     example, the following statement prints a message and then waits 5
     seconds before clearing the screen.

          fprintf (stderr, "wait please...\n");
          pause (5);
          clc;

 -- Built-in Function:  sleep (SECONDS)
     Suspend the execution of the program for the given number of
     seconds.

 -- Built-in Function:  usleep (MICROSECONDS)
     Suspend the execution of the program for the given number of
     microseconds.  On systems where it is not possible to sleep for
     periods of time less than one second, `usleep' will pause the
     execution for `round (MICROSECONDS / 1e6)' seconds.

 -- Function File: DAYS = datenum (DATEVEC)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE,
          SECOND)
 -- Function File: DAYS = datenum ("datestr")
 -- Function File: DAYS = datenum ("datestr", P)
 -- Function File: [DAYS, SECS] = datenum (...)
     Return the date/time input as a serial day number, with Jan 1, 0000
     defined as day 1.

     The integer part, `floor (DAYS)' counts the number of complete
     days in the date input.

     The fractional part, `rem (DAYS, 1)' corresponds to the time on
     the given day.

     The input may be a date vector (see `datevec'), datestr (see
     `datestr'), or directly specified as input.

     When processing input datestrings, P is the year at the start of
     the century to which two-digit years will be referenced.  If not
     specified, it defaults to the current year minus 50.

     The optional output SECS holds the time on the specified day with
     greater precision than DAYS.

     Notes:

        * Years can be negative and/or fractional.

        * Months below 1 are considered to be January.

        * Days of the month start at 1.

        * Days beyond the end of the month go into subsequent months.

        * Days before the beginning of the month go to the previous
          month.

        * Days can be fractional.

     *Caution:* this function does not attempt to handle Julian
     calendars so dates before Octave 15, 1582 are wrong by as much as
     eleven days.  Also, be aware that only Roman Catholic countries
     adopted the calendar in 1582.  It took until 1924 for it to be
     adopted everywhere.  See the Wikipedia entry on the Gregorian
     calendar for more details.

     *Warning:* leap seconds are ignored.  A table of leap seconds is
     available on the Wikipedia entry for leap seconds.

     *See also:* *note datestr: doc-datestr, *note datevec:
     doc-datevec, *note now: doc-now, *note clock: doc-clock, *note
     date: doc-date.

 -- Function File: STR = datestr (DATE)
 -- Function File: STR = datestr (DATE, F)
 -- Function File: STR = datestr (DATE, F, P)
     Format the given date/time according to the format `f' and return
     the result in STR.  DATE is a serial date number (see `datenum')
     or a date vector (see `datevec').  The value of DATE may also be a
     string or cell array of strings.

     F can be an integer which corresponds to one of the codes in the
     table below, or a date format string.

     P is the year at the start of the century in which two-digit years
     are to be interpreted in.  If not specified, it defaults to the
     current year minus 50.

     For example, the date 730736.65149 (2000-09-07 15:38:09.0934)
     would be formatted as follows:

     Code    Format                         Example
     --------------------------------------------------------------- 
     0       dd-mmm-yyyy HH:MM:SS           07-Sep-2000 15:38:09
     1       dd-mmm-yyyy                    07-Sep-2000
     2       mm/dd/yy                       09/07/00
     3       mmm                            Sep
     4       m                              S
     5       mm                             09
     6       mm/dd                          09/07
     7       dd                             07
     8       ddd                            Thu
     9       d                              T
     10      yyyy                           2000
     11      yy                             00
     12      mmmyy                          Sep00
     13      HH:MM:SS                       15:38:09
     14      HH:MM:SS PM                    03:38:09 PM
     15      HH:MM                          15:38
     16      HH:MM PM                       03:38 PM
     17      QQ-YY                          Q3-00
     18      QQ                             Q3
     19      dd/mm                          13/03
     20      dd/mm/yy                       13/03/95
     21      mmm.dd.yyyy HH:MM:SS           Mar.03.1962 13:53:06
     22      mmm.dd.yyyy                    Mar.03.1962
     23      mm/dd/yyyy                     03/13/1962
     24      dd/mm/yyyy                     12/03/1962
     25      yy/mm/dd                       95/03/13
     26      yyyy/mm/dd                     1995/03/13
     27      QQ-YYYY                        Q4-2132
     28      mmmyyyy                        Mar2047
     29      yyyymmdd                       20470313
     30      yyyymmddTHHMMSS                20470313T132603
     31      yyyy-mm-dd HH:MM:SS            1047-03-13 13:26:03

     If F is a format string, the following symbols are recognized:

     Symbol  Meaning                                         Example
     ---------------------------------------------------------------------- 
     yyyy    Full year                                       2005
     yy      Two-digit year                                  2005
     mmmm    Full month name                                 December
     mmm     Abbreviated month name                          Dec
     mm      Numeric month number (padded with zeros)        01, 08, 12
     m       First letter of month name (capitalized)        D
     dddd    Full weekday name                               Sunday
     ddd     Abbreviated weekday name                        Sun
     dd      Numeric day of month (padded with zeros)        11
     d       First letter of weekday name (capitalized)      S
     HH      Hour of day, padded with zeros if PM is set     09:00
             and not padded with zeros otherwise             9:00 AM
     MM      Minute of hour (padded with zeros)              10:05
     SS      Second of minute (padded with zeros)            10:05:03
     FFF     Milliseconds of second (padded with zeros)      10:05:03.012
     AM      Use 12-hour time format                         11:30 AM
     PM      Use 12-hour time format                         11:30 PM

     If F is not specified or is `-1', then use 0, 1 or 16, depending
     on whether the date portion or the time portion of DATE is empty.

     If P is nor specified, it defaults to the current year minus 50.

     If a matrix or cell array of dates is given, a column vector of
     date strings is returned.

     *See also:* *note datenum: doc-datenum, *note datevec:
     doc-datevec, *note date: doc-date, *note now: doc-now, *note
     clock: doc-clock.

 -- Function File: V = datevec (DATE)
 -- Function File: V = datevec (DATE, F)
 -- Function File: V = datevec (DATE, P)
 -- Function File: V = datevec (DATE, F, P)
 -- Function File: [Y, M, D, H, MI, S] = datevec (...)
     Convert a serial date number (see `datenum') or date string (see
     `datestr') into a date vector.

     A date vector is a row vector with six members, representing the
     year, month, day, hour, minute, and seconds respectively.

     F is the format string used to interpret date strings (see
     `datestr').

     P is the year at the start of the century to which two-digit years
     will be referenced.  If not specified, it defaults to the current
     year minus 50.

     *See also:* *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note clock: doc-clock, *note now: doc-now, *note
     date: doc-date.

 -- Function File: D = addtodate (D, Q, F)
     Add Q amount of time (with units F) to the serial datenum, D.

     F must be one of "year", "month", "day", "hour", "minute",
     "second", or "millisecond".

     *See also:* *note datenum: doc-datenum, *note datevec:
     doc-datevec, *note etime: doc-etime.

 -- Function File: C = calendar ()
 -- Function File: C = calendar (D)
 -- Function File: C = calendar (Y, M)
 -- Function File:  calendar (...)
     Return the current monthly calendar in a 6x7 matrix.

     If D is specified, return the calendar for the month containing
     the date D, which must be a serial date number or a date string.

     If Y and M are specified, return the calendar for year Y and month
     M.

     If no output arguments are specified, print the calendar on the
     screen instead of returning a matrix.

     *See also:* *note datenum: doc-datenum, *note datestr: doc-datestr.

 -- Function File: [N, S] = weekday (D)
 -- Function File: [N, S] = weekday (D, FORMAT)
     Return the day of the week as a number in N and as a string in S.
     The days of the week are numbered 1-7 with the first day being
     Sunday.

     D is a serial date number or a date string.

     If the string FORMAT is not present or is equal to "short" then S
     will contain the abbreviated name of the weekday.  If FORMAT is
     "long" then S will contain the full name.

     Table of return values based on FORMAT:

     N    "short"   "long"
     --------------------------- 
     1    Sun       Sunday
     2    Mon       Monday
     3    Tue       Tuesday
     4    Wed       Wednesday
     5    Thu       Thursday
     6    Fri       Friday
     7    Sat       Saturday

     *See also:* *note eomday: doc-eomday, *note is_leap_year:
     doc-is_leap_year, *note calendar: doc-calendar, *note datenum:
     doc-datenum, *note datevec: doc-datevec.

 -- Function File: E = eomday (Y, M)
     Return the last day of the month M for the year Y.

     *See also:* *note weekday: doc-weekday, *note datenum:
     doc-datenum, *note datevec: doc-datevec, *note is_leap_year:
     doc-is_leap_year, *note calendar: doc-calendar.

 -- Function File:  datetick ()
 -- Function File:  datetick (FORM)
 -- Function File:  datetick (AXIS, FORM)
 -- Function File:  datetick (..., "keeplimits")
 -- Function File:  datetick (..., "keepticks")
 -- Function File:  datetick (...ax, ...)
     Add date formatted tick labels to an axis.  The axis the apply the
     ticks to is determined by AXIS that can take the values "x", "y"
     or "z".  The default value is "x".  The formatting of the labels is
     determined by the variable FORM, that can either be a string in
     the format needed by `dateform', or a positive integer that can be
     accepted by `datestr'.

     *See also:* *note datenum: doc-datenum, *note datestr: doc-datestr.


File: octave.info,  Node: Filesystem Utilities,  Next: File Archiving Utilities,  Prev: Timing Utilities,  Up: System Utilities

36.2 Filesystem Utilities
=========================

Octave includes many utility functions for copying, moving, renaming,
and deleting files; for creating, reading, and deleting directories;
for retrieving status information on files; and for manipulating file
and path names.

 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2, 'f')
     Move the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.  If the force flag 'f' is given then any existing
     files will be overwritten without prompting.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note rename: doc-rename, *note copyfile: doc-copyfile.

 -- Built-in Function: [ERR, MSG] = rename (OLD, NEW)
     Change the name of file OLD to NEW.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note ls: doc-ls, *note dir: doc-dir.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, 'f')
     Copy the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.  If the force flag 'f' is given then existing
     destination files will be overwritten without prompting.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note movefile: doc-movefile.

 -- Built-in Function: [ERR, MSG] = unlink (FILE)
     Delete the file named FILE.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [ERR, MSG] = link (OLD, NEW)
     Create a new link (also known as a hard link) to an existing file.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note symlink: doc-symlink.

 -- Built-in Function: [ERR, MSG] = symlink (OLD, NEW)
     Create a symbolic link NEW which contains the string OLD.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note link: doc-link, *note readlink: doc-readlink.

 -- Built-in Function: [RESULT, ERR, MSG] = readlink (SYMLINK)
     Read the value of the symbolic link SYMLINK.

     If successful, RESULT contains the contents of the symbolic link
     SYMLINK, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     *See also:* *note link: doc-link, *note symlink: doc-symlink.

 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (PARENT, DIR)
     Create a directory named DIR in the directory PARENT.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note rmdir: doc-rmdir.

 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR, "s")
     Remove the directory named DIR.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     If the optional second parameter is supplied with value `"s"',
     recursively remove all subdirectories as well.

     *See also:* *note mkdir: doc-mkdir, *note confirm_recursive_rmdir:
     doc-confirm_recursive_rmdir.

 -- Built-in Function: VAL = confirm_recursive_rmdir ()
 -- Built-in Function: OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
 -- Built-in Function:  confirm_recursive_rmdir (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will ask for confirmation before recursively removing a directory
     tree.

     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.

 -- Built-in Function: [ERR, MSG] = mkfifo (NAME, MODE)
     Create a FIFO special file named NAME with file mode MODE

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function:  umask (MASK)
     Set the permission mask for file creation.  The parameter MASK is
     an integer, interpreted as an octal number.  If successful,
     returns the previous value of the mask (as an integer to be
     interpreted as an octal number); otherwise an error message is
     printed.

 -- Built-in Function: [INFO, ERR, MSG] = stat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = stat (FID)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FID)
     Return a structure INFO containing the following information about
     FILE or file identifier FID.

    `dev'
          ID of device containing a directory entry for this file.

    `ino'
          File number of the file.

    `mode'
          File mode, as an integer.  Use the functions `S_ISREG',
          `S_ISDIR', `S_ISCHR', `S_ISBLK', `S_ISFIFO', `S_ISLNK', or
          `S_ISSOCK' to extract information from this value.

    `modestr'
          File mode, as a string of ten letters or dashes as would be
          returned by `ls -l'.

    `nlink'
          Number of links.

    `uid'
          User ID of file's owner.

    `gid'
          Group ID of file's group.

    `rdev'
          ID of device for block or character special files.

    `size'
          Size in bytes.

    `atime'
          Time of last access in the same form as time values returned
          from `time'.  *Note Timing Utilities::.

    `mtime'
          Time of last modification in the same form as time values
          returned from `time'.  *Note Timing Utilities::.

    `ctime'
          Time of last file status change in the same form as time
          values returned from `time'.  *Note Timing Utilities::.

    `blksize'
          Size of blocks in the file.

    `blocks'
          Number of blocks allocated for file.

     If the call is successful ERR is 0 and MSG is an empty string.  If
     the file does not exist, or some other error occurs, S is an empty
     matrix, ERR is -1, and MSG contains the corresponding system error
     message.

     If FILE is a symbolic link, `stat' will return information about
     the actual file that is referenced by the link.  Use `lstat' if
     you want information about the symbolic link itself.

     For example:

          [s, err, msg] = stat ("/vmlinuz")
                => s =
                  {
                    atime = 855399756
                    rdev = 0
                    ctime = 847219094
                    uid = 0
                    size = 389218
                    blksize = 4096
                    mtime = 847219094
                    gid = 6
                    nlink = 1
                    blocks = 768
                    mode = -rw-r--r--
                    modestr = -rw-r--r--
                    ino = 9316
                    dev = 2049
                  }
               => err = 0
               => msg =

 -- Built-in Function:  S_ISBLK (MODE)
     Return true if MODE corresponds to a block device.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISCHR (MODE)
     Return true if MODE corresponds to a character device.  The value
     of MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISDIR (MODE)
     Return true if MODE corresponds to a directory.  The value of MODE
     is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISFIFO (MODE)
     Return true if MODE corresponds to a fifo.  The value of MODE is
     assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISLNK (MODE)
     Return true if MODE corresponds to a symbolic link.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISREG (MODE)
     Return true if MODE corresponds to a regular file.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISSOCK (MODE)
     Return true if MODE corresponds to a socket.  The value of MODE is
     assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Function File: [STATUS, RESULT, MSGID] = fileattrib (FILE)
     Return information about FILE.

     If successful, STATUS is 1, with RESULT containing a structure
     with the following fields:

    `Name'
          Full name of FILE.

    `archive'
          True if FILE is an archive (Windows).

    `system'
          True if FILE is a system file (Windows).

    `hidden'
          True if FILE is a hidden file (Windows).

    `directory'
          True if FILE is a directory.

    `UserRead'
    `GroupRead'
    `OtherRead'
          True if the user (group; other users) has read permission for
          FILE.

    `UserWrite'
    `GroupWrite'
    `OtherWrite'
          True if the user (group; other users) has write permission for
          FILE.

    `UserExecute'
    `GroupExecute'
    `OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.
     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

     With no input arguments, return information about the current
     directory.

     If FILE contains globbing characters, return information about all
     the matching files.

     *See also:* *note glob: doc-glob.

 -- Function File:  isdir (F)
     Return true if F is a directory.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note is_rooted_relative_filename: doc-is_rooted_relative_filename.

 -- Built-in Function: [FILES, ERR, MSG] = readdir (DIR)
     Return names of the files in the directory DIR as a cell array of
     strings.  If an error occurs, return an empty cell array in FILES.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note ls: doc-ls, *note dir: doc-dir, *note glob:
     doc-glob.

 -- Built-in Function:  glob (PATTERN)
     Given an array of pattern strings (as a char array or a cell
     array) in PATTERN, return a cell array of file names that match
     any of them, or an empty cell array if no patterns match.  The
     pattern strings are interpreted as filename globbing patterns (as
     they are used by Unix shells).  Within a pattern
    `*'
          matches any string, including the null string,

    `?'
          matches any single character, and

    `[...]'
          matches any of the enclosed characters.

     Tilde expansion is performed on each of the patterns before
     looking for matching file names.  For example:

          ls
               =>
                  file1  file2  file3  myfile1 myfile1b
          glob ("*file1")
               =>
                  {
                    [1,1] = file1
                    [2,1] = myfile1
                  }
          glob ("myfile?")
               =>
                  {
                    [1,1] = myfile1
                  }
          glob ("file[12]")
               =>
                  {
                    [1,1] = file1
                    [2,1] = file2
                  }

     *See also:* *note ls: doc-ls, *note dir: doc-dir, *note readdir:
     doc-readdir.

 -- Built-in Function:  fnmatch (PATTERN, STRING)
     Return 1 or zero for each element of STRING that matches any of
     the elements of the string array PATTERN, using the rules of
     filename pattern matching.  For example:

          fnmatch ("a*b", {"ab"; "axyzb"; "xyzab"})
               => [ 1; 1; 0 ]

 -- Built-in Function:  file_in_path (PATH, FILE)
 -- Built-in Function:  file_in_path (PATH, FILE, "all")
     Return the absolute name of FILE if it can be found in PATH.  The
     value of PATH should be a colon-separated list of directories in
     the format described for `path'.  If no file is found, return an
     empty character string.  For example:

          file_in_path (EXEC_PATH, "sh")
               => "/bin/sh"

     If the second argument is a cell array of strings, search each
     directory of the path for element of the cell array and return the
     first that matches.

     If the third optional argument `"all"' is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

     *See also:* *note file_in_loadpath: doc-file_in_loadpath.

 -- Built-in Function:  filesep ()
 -- Built-in Function:  filesep ('all')
     Return the system-dependent character used to separate directory
     names.

     If 'all' is given, the function returns all valid file separators
     in the form of a string.  The list of file separators is
     system-dependent.  It is `/' (forward slash) under UNIX or
     Mac OS X, `/' and `\' (forward and backward slashes) under Windows.

     *See also:* *note pathsep: doc-pathsep.

 -- Built-in Function: VAL = filemarker ()
 -- Built-in Function:  filemarker (NEW_VAL)
 -- Built-in Function:  filemarker (NEW_VAL, "local")
     Query or set the character used to separate filename from the the
     subfunction names contained within the file.  This can be used in
     a generic manner to interact with subfunctions.  For example,

          help (["myfunc", filemarker, "mysubfunc"])

     returns the help string associated with the sub-function
     `mysubfunc' of the function `myfunc'.  Another use of `filemarker'
     is when debugging it allows easier placement of breakpoints within
     sub-functions.  For example,

          dbstop (["myfunc", filemarker, "mysubfunc"])

     will set a breakpoint at the first line of the subfunction
     `mysubfunc'.

     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.

 -- Function File: [DIR, NAME, EXT, VER] = fileparts (FILENAME)
     Return the directory, name, extension, and version components of
     FILENAME.

     *See also:* *note fullfile: doc-fullfile.

 -- Function File: FILENAME = fullfile (DIR1, DIR2, ..., FILE)
     Return a complete filename constructed from the given components.

     *See also:* *note fileparts: doc-fileparts.

 -- Built-in Function:  tilde_expand (STRING)
     Perform tilde expansion on STRING.  If STRING begins with a tilde
     character, (`~'), all of the characters preceding the first slash
     (or all characters, if there is no slash) are treated as a
     possible user name, and the tilde and the following characters up
     to the slash are replaced by the home directory of the named user.
     If the tilde is followed immediately by a slash, the tilde is
     replaced by the home directory of the user running Octave.  For
     example:

          tilde_expand ("~joeuser/bin")
               => "/home/joeuser/bin"
          tilde_expand ("~/bin")
               => "/home/jwe/bin"

 -- Built-in Function: [CNAME, STATUS, MSG] canonicalize_file_name
          (NAME)
     Return the canonical name of file NAME.

 -- Built-in Function:  make_absolute_filename (FILE)
     Return the full name of FILE, relative to the current directory.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note is_rooted_relative_filename:
     doc-is_rooted_relative_filename, *note isdir: doc-isdir.

 -- Built-in Function:  is_absolute_filename (FILE)
     Return true if FILE is an absolute filename.

     *See also:* *note is_rooted_relative_filename:
     doc-is_rooted_relative_filename, *note make_absolute_filename:
     doc-make_absolute_filename, *note isdir: doc-isdir.

 -- Built-in Function:  is_rooted_relative_filename (FILE)
     Return true if FILE is a rooted-relative filename.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note make_absolute_filename: doc-make_absolute_filename, *note
     isdir: doc-isdir.

 -- Built-in Function:  P_tmpdir ()
     Return the default name of the directory for temporary files on
     this system.  The name of this directory is system dependent.

 -- Function File: DIR = tempdir ()
     Return the name of the system's directory for temporary files.

 -- Function File:  tempname ()
 -- Function File:  tempname (DIR)
 -- Function File:  tempname (DIR, PREFIX)
     This function is an alias for `tmpnam'.

     *See also:* *note tmpnam: doc-tmpnam.

 -- Function File: CURRENT_STATE recycle ()
 -- Function File: OLD_STATE recycle (NEW_STATE)
     Query or set the preference for recycling deleted files.

     Recycling files instead of permanently deleting them is currently
     not implemented in Octave.  To help avoid accidental data loss it
     is an error to attempt enable file recycling.

     *See also:* *note delete: doc-delete.


File: octave.info,  Node: File Archiving Utilities,  Next: Networking Utilities,  Prev: Filesystem Utilities,  Up: System Utilities

36.3 File Archiving Utilities
=============================

 -- Function File:  bunzip2 (BZFILE)
 -- Function File:  bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note bzip2: doc-bzip2, *note unpack: doc-unpack,
     *note gunzip: doc-gunzip, *note unzip: doc-unzip, *note untar:
     doc-untar.

 -- Function File: ENTRIES = gzip (FILES)
 -- Function File: ENTRIES = gzip (FILES, OUTDIR)
     Compress the list of files and/or directories specified in FILES.
     Each file is compressed separately and a new file with a '.gz'
     extension is created.  The original files are not modified.
     Existing compressed files are silently overwritten.  If OUTDIR is
     defined the compressed files are placed in this directory.

     *See also:* *note gunzip: doc-gunzip, *note bzip2: doc-bzip2,
     *note zip: doc-zip, *note tar: doc-tar.

 -- Function File:  gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.  If GZFILE is
     a directory, all gzfiles in the directory will be recursively
     gunzipped.

     *See also:* *note gzip: doc-gzip, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note unzip: doc-unzip, *note untar:
     doc-untar.

 -- Function File: ENTRIES = tar (TARFILE, FILES)
 -- Function File: ENTRIES = tar (TARFILE, FILES, ROOT)
     Pack FILES FILES into the TAR archive TARFILE.  The list of files
     must be a string or a cell array of strings.

     The optional argument ROOT changes the relative path of FILES from
     the current directory.

     If an output argument is requested the entries in the archive are
     returned in a cell array.

     *See also:* *note untar: doc-untar, *note bzip2: doc-bzip2, *note
     gzip: doc-gzip, *note zip: doc-zip.

 -- Function File:  untar (TARFILE)
 -- Function File:  untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note tar: doc-tar, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note gunzip: doc-gunzip, *note unzip:
     doc-unzip.

 -- Function File: ENTRIES = zip (ZIPFILE, FILES)
 -- Function File: ENTRIES = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and/or directories specified in FILES
     into the archive ZIPFILE in the same directory.  If ROOTDIR is
     defined the FILES are located relative to ROOTDIR rather than the
     current directory.

     *See also:* *note unzip: doc-unzip, *note bzip2: doc-bzip2, *note
     gzip: doc-gzip, *note tar: doc-tar.

 -- Function File:  unzip (ZIPFILE)
 -- Function File:  unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note zip: doc-zip, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note gunzip: doc-gunzip, *note untar:
     doc-untar.

 -- Function File: FILES = unpack (FILE)
 -- Function File: FILES = unpack (FILE, DIR)
 -- Function File: FILES = unpack (FILE, DIR, FILETYPE)
     Unpack the archive FILE based on its extension to the directory
     DIR.  If FILE is a list of strings, then each file is unpacked
     individually.  If DIR is not specified, it defaults to the current
     directory.  If a directory is in the file list, then the FILETYPE
     must also be specified.

     The optional return value is a list of FILES unpacked.

     *See also:* *note bzip2: doc-bzip2, *note gzip: doc-gzip, *note
     zip: doc-zip, *note tar: doc-tar.

 -- Function File: ENTRIES = bzip2 (FILES)
 -- Function File: ENTRIES = bzip2 (FILES, OUTDIR)
     Compress the list of files specified in FILES.  Each file is
     compressed separately and a new file with a '.bz2' extension is
     created.  The original files are not modified.  Existing
     compressed files are silently overwritten.  If OUTDIR is defined
     the compressed files are placed in this directory.

     *See also:* *note bunzip2: doc-bunzip2, *note gzip: doc-gzip,
     *note zip: doc-zip, *note tar: doc-tar.


File: octave.info,  Node: Networking Utilities,  Next: Controlling Subprocesses,  Prev: File Archiving Utilities,  Up: System Utilities

36.4 Networking Utilities
=========================

* Menu:

* FTP Objects::
* URL Manipulation::

 -- Built-in Function:  gethostname ()
     Return the hostname of the system where Octave is running.


File: octave.info,  Node: FTP Objects,  Next: URL Manipulation,  Up: Networking Utilities

36.4.1 FTP Objects
------------------

 -- Function File: F = ftp (HOST)
 -- Function File: F = ftp (HOST, USERNAME, PASSWORD)
     Connect to the FTP server HOST with USERNAME and PASSWORD.  If
     USERNAME and PASSWORD are not specified, user "anonymous" with no
     password is used.  The returned FTP object F represents the
     established FTP connection.

 -- Function File:  mget (F, FILE)
 -- Function File:  mget (F, DIR)
 -- Function File:  mget (..., TARGET)
     Download a remote file FILE or directory DIR to the local
     directory on the FTP connection F.  F is an FTP object returned by
     the `ftp' function.

     The arguments FILE and DIR can include wildcards and any files or
     directories on the remote server that match will be downloaded.

     If a third argument TARGET is given, then a single file or
     directory will be downloaded with the name TARGET to the local
     directory.

 -- Function File:  mput (F, FILE)
     Upload the local file FILE into the current remote directory on
     the FTP connection F.  F is an FTP object returned by the ftp
     function.

     The argument FILE is passed by the "glob" function and any files
     that match the wildcards in FILE will be uploaded.

 -- Function File:  ascii (F)
     Put the FTP connection F into ascii mode.  F is an FTP object
     returned by the `ftp' function.

 -- Function File:  binary (F)
     Put the FTP connection F into binary mode.  F is an FTP object
     returned by the `ftp' function.


File: octave.info,  Node: URL Manipulation,  Prev: FTP Objects,  Up: Networking Utilities

36.4.2 URL Manipulation
-----------------------

 -- Loadable Function: S = urlread (URL)
 -- Loadable Function: [S, SUCCESS] = urlread (URL)
 -- Loadable Function: [S, SUCCESS, MESSAGE] = urlread (URL)
 -- Loadable Function: [...] = urlread (URL, METHOD, PARAM)
     Download a remote file specified by its URL and return its content
     in string S.  For example:

          s = urlread ("ftp://ftp.octave.org/pub/octave/README");

     The variable SUCCESS is 1 if the download was successful,
     otherwise it is 0 in which case MESSAGE contains an error message.
     If no output argument is specified and an error occurs, then the
     error is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL.  For example:

          s = urlread ("http://user:password@example.com/file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example:

          s = urlread ("http://www.google.com/search", "get",
                       {"query", "octave"});

     *See also:* *note urlwrite: doc-urlwrite.

 -- Loadable Function:  urlwrite (URL, LOCALFILE)
 -- Loadable Function: F = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS] = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS, MESSAGE] = urlwrite (URL, LOCALFILE)
     Download a remote file specified by its URL and save it as
     LOCALFILE.  For example:

          urlwrite ("ftp://ftp.octave.org/pub/octave/README",
                    "README.txt");

     The full path of the downloaded file is returned in F.  The
     variable SUCCESS is 1 if the download was successful, otherwise it
     is 0 in which case MESSAGE contains an error message.  If no
     output argument is specified and an error occurs, then the error
     is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL, for example:

          urlwrite ("http://username:password@example.com/file.txt",
                    "file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example:

          urlwrite ("http://www.google.com/search", "search.html",
                    "get", {"query", "octave"});

     *See also:* *note urlread: doc-urlread.


File: octave.info,  Node: Controlling Subprocesses,  Next: Process ID Information,  Prev: Networking Utilities,  Up: System Utilities

36.5 Controlling Subprocesses
=============================

Octave includes some high-level commands like `system' and `popen' for
starting subprocesses.  If you want to run another program to perform
some task and then look at its output, you will probably want to use
these functions.

   Octave also provides several very low-level Unix-like functions which
can also be used for starting subprocesses, but you should probably only
use them if you can't find any way to do what you need with the
higher-level functions.

 -- Built-in Function:  system ("STRING")
 -- Built-in Function:  system ("STRING", RETURN_OUTPUT)
 -- Built-in Function:  system ("STRING", RETURN_OUTPUT, TYPE)
 -- Built-in Function: [STATUS, OUTPUT] = system (...)
     Execute a shell command specified by STRING.  If the optional
     argument TYPE is "async", the process is started in the background
     and the process ID of the child process is returned immediately.
     Otherwise, the child process is started and Octave waits until it
     exits.  If the TYPE argument is omitted, it defaults to the value
     "sync".

     If SYSTEM is called with one or more output arguments, or if the
     optional argument RETURN_OUTPUT is true and the subprocess is
     started synchronously, then the output from the command is
     returned as a variable.  Otherwise, if the subprocess is executed
     synchronously, its output is sent to the standard output.  To send
     the output of a command executed with `system' through the pager,
     use a command like

          [output, text] = system ("cmd");
          disp (text);

     or

          printf ("%s\n", nthargout (2, "system", "cmd"));

     The `system' function can return two values.  The first is the
     exit status of the command and the second is any output from the
     command that was written to the standard output stream.  For
     example,

          [status, output] = system ("echo foo; exit 2");

     will set the variable `output' to the string `foo', and the
     variable `status' to the integer `2'.

     For commands run asynchronously, STATUS is the process id of the
     command shell that is started to run the command.

     *See also:* *note unix: doc-unix, *note dos: doc-dos.

 -- Function File:  unix ("COMMAND")
 -- Function File: STATUS = unix ("COMMAND")
 -- Function File: [STATUS, TEXT] = unix ("COMMAND")
 -- Function File: [...] = unix ("COMMAND", "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output from the command in TEXT.  When
     called with no output argument, or the "-echo" argument is given,
     then TEXT is also sent to standard output.

     *See also:* *note dos: doc-dos, *note system: doc-system, *note
     isunix: doc-isunix, *note ispc: doc-ispc.

 -- Function File:  dos ("COMMAND")
 -- Function File: STATUS = dos ("COMMAND")
 -- Function File: [STATUS, TEXT] = dos ("COMMAND")
 -- Function File: [...] = dos ("COMMAND", "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output from the command in TEXT.  When
     called with no output argument, or the "-echo" argument is given,
     then TEXT is also sent to standard output.

     *See also:* *note unix: doc-unix, *note system: doc-system, *note
     isunix: doc-isunix, *note ispc: doc-ispc.

 -- Function File: [OUTPUT, STATUS] = perl (SCRIPTFILE)
 -- Function File: [OUTPUT, STATUS] = perl (SCRIPTFILE, ARGUMENT1,
          ARGUMENT2, ...)
     Invoke Perl script SCRIPTFILE with possibly a list of command line
     arguments.  Returns output in OUTPUT and status in STATUS.

     *See also:* *note system: doc-system.

 -- Function File: [OUTPUT, STATUS] = python (SCRIPTFILE)
 -- Function File: [OUTPUT, STATUS] = python (SCRIPTFILE, ARGUMENT1,
          ARGUMENT2, ...)
     Invoke python script SCRIPTFILE with possibly a list of command
     line arguments.  Returns output in OUTPUT and status in STATUS.

     *See also:* *note system: doc-system.

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.  The name of the command to run
     is given by COMMAND.  The file identifier corresponding to the
     input or output stream of the process is returned in FID.  The
     argument MODE may be

    `"r"'
          The pipe will be connected to the standard output of the
          process, and open for reading.

    `"w"'
          The pipe will be connected to the standard input of the
          process, and open for writing.

     For example:

          fid = popen ("ls -ltr / | tail -3", "r");
          while (ischar (s = fgets (fid)))
            fputs (stdout, s);
          endwhile
               -| drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
               -| drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
               -| drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

 -- Built-in Function:  pclose (FID)
     Close a file identifier that was opened by `popen'.  You may also
     use `fclose' for the same purpose.

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.  The name of the
     process is given by COMMAND, and ARGS is an array of strings
     containing options for the command.  The file identifiers for the
     input and output streams of the subprocess are returned in IN and
     OUT.  If execution of the command is successful, PID contains the
     process ID of the subprocess.  Otherwise, PID is -1.

     For example:

          [in, out, pid] = popen2 ("sort", "-r");
          fputs (in, "these\nare\nsome\nstrings\n");
          fclose (in);
          EAGAIN = errno ("EAGAIN");
          done = false;
          do
            s = fgets (out);
            if (ischar (s))
              fputs (stdout, s);
            elseif (errno () == EAGAIN)
              sleep (0.1);
              fclear (out);
            else
              done = true;
            endif
          until (done)
          fclose (out);
          waitpid (pid);
               -| these
               -| strings
               -| some
               -| are

     Note that `popen2', unlike `popen', will not "reap" the child
     process.  If you don't use `waitpid' to check the child's exit
     status, it will linger until Octave exits.

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
 -- Built-in Function:  EXEC_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated
     list of directories to append to the shell PATH when executing
     external programs.  The initial value of is taken from the
     environment variable `OCTAVE_EXEC_PATH', but that value can be
     overridden by the command line argument `--exec-path PATH'.

     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.

   In most cases, the following functions simply decode their arguments
and make the corresponding Unix system calls.  For a complete example
of how they can be used, look at the definition of the function
`popen2'.

 -- Built-in Function: [PID, MSG] = fork ()
     Create a copy of the current process.

     Fork can return one of the following values:

    > 0
          You are in the parent process.  The value returned from
          `fork' is the process id of the child process.  You should
          probably arrange to wait for any child processes to exit.

    0
          You are in the child process.  You can call `exec' to start
          another process.  If that fails, you should probably call
          `exit'.

    < 0
          The call to `fork' failed for some reason.  You must take
          evasive action.  A system dependent error message will be
          waiting in MSG.

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.  Calling `exec' without
     first calling `fork' will terminate your current Octave process and
     replace it with the program named by FILE.  For example,

          exec ("ls" "-l")

     will run `ls' and return you to your shell prompt.

     If successful, `exec' does not return.  If `exec' does return, ERR
     will be nonzero, and MSG will contain a system-dependent error
     message.

 -- Built-in Function: [READ_FD, WRITE_FD, ERR, MSG] = pipe ()
     Create a pipe and return the reading and writing ends of the pipe
     into READ_FD and WRITE_FD respectively.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [FID, MSG] = dup2 (OLD, NEW)
     Duplicate a file descriptor.

     If successful, FID is greater than zero and contains the new file
     ID.  Otherwise, FID is negative and MSG contains a
     system-dependent error message.

 -- Built-in Function: [PID, STATUS, MSG] = waitpid (PID, OPTIONS)
     Wait for process PID to terminate.  The PID argument can be:

    -1
          Wait for any child process.

    0
          Wait for any child process whose process group ID is equal to
          that of the Octave interpreter process.

    > 0
          Wait for termination of the child process with ID PID.

     The OPTIONS argument can be a bitwise OR of zero or more of the
     following constants:

    `0'
          Wait until signal is received or a child process exits (this
          is the default if the OPTIONS argument is missing).

    `WNOHANG'
          Do not hang if status is not immediately available.

    `WUNTRACED'
          Report the status of any child processes that are stopped,
          and whose status has not yet been reported since they stopped.

    `WCONTINUE'
          Return if a stopped child has been resumed by delivery of
          `SIGCONT'.  This value may not be meaningful on all systems.

     If the returned value of PID is greater than 0, it is the process
     ID of the child process that exited.  If an error occurs, PID will
     be less than zero and MSG will contain a system-dependent error
     message.  The value of STATUS contains additional system-dependent
     information about the subprocess that exited.

     *See also:* *note WCONTINUE: doc-WCONTINUE, *note WCOREDUMP:
     doc-WCOREDUMP, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFCONTINUED: doc-WIFCONTINUED, *note WIFSIGNALED:
     doc-WIFSIGNALED, *note WIFSTOPPED: doc-WIFSTOPPED, *note WNOHANG:
     doc-WNOHANG, *note WSTOPSIG: doc-WSTOPSIG, *note WTERMSIG:
     doc-WTERMSIG, *note WUNTRACED: doc-WUNTRACED.

 -- Built-in Function:  WCONTINUE ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should also return if a
     stopped child has been resumed by delivery of a `SIGCONT' signal.

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WUNTRACED: doc-WUNTRACED.

 -- Built-in Function:  WCOREDUMP (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     produced a core dump.  This function should only be employed if
     `WIFSIGNALED' returned true.  The macro used to implement this
     function is not specified in POSIX.1-2001 and is not available on
     some Unix implementations (e.g., AIX, SunOS).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WEXITSTATUS (STATUS)
     Given STATUS from a call to `waitpid', return the exit status of
     the child.  This function should only be employed if `WIFEXITED'
     returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

 -- Built-in Function:  WIFCONTINUED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was resumed by delivery of `SIGCONT'.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WSTOPSIG: doc-WSTOPSIG.

 -- Built-in Function:  WIFSIGNALED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was terminated by a signal.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

 -- Built-in Function:  WIFSTOPPED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was stopped by delivery of a signal; this is only possible
     if the call was done using `WUNTRACED' or when the child is being
     traced (see ptrace(2)).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WIFEXITED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     terminated normally.

     *See also:* *note waitpid: doc-waitpid, *note WEXITSTATUS:
     doc-WEXITSTATUS, *note WIFSIGNALED: doc-WIFSIGNALED, *note
     WTERMSIG: doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WNOHANG ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should return its status
     immediately instead of waiting for a process to exit.

     *See also:* *note waitpid: doc-waitpid, *note WUNTRACED:
     doc-WUNTRACED, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function:  WSTOPSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal which caused the child to stop.  This function should only
     be employed if `WIFSTOPPED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WTERMSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal that caused the child process to terminate.  This function
     should only be employed if `WIFSIGNALED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WCOREDUMP: doc-WCOREDUMP,
     *note WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG,
     *note WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WUNTRACED ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should also return if the
     child process has stopped but is not traced via the `ptrace'
     system call

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function: [ERR, MSG] = fcntl (FID, REQUEST, ARG)
     Change the properties of the open file FID.  The following values
     may be passed as REQUEST:

    `F_DUPFD'
          Return a duplicate file descriptor.

    `F_GETFD'
          Return the file descriptor flags for FID.

    `F_SETFD'
          Set the file descriptor flags for FID.

    `F_GETFL'
          Return the file status flags for FID.  The following codes
          may be returned (some of the flags may be undefined on some
          systems).

         `O_RDONLY'
               Open for reading only.

         `O_WRONLY'
               Open for writing only.

         `O_RDWR'
               Open for reading and writing.

         `O_APPEND'
               Append on each write.

         `O_CREAT'
               Create the file if it does not exist.

         `O_NONBLOCK'
               Non-blocking mode.

         `O_SYNC'
               Wait for writes to complete.

         `O_ASYNC'
               Asynchronous I/O.

    `F_SETFL'
          Set the file status flags for FID to the value specified by
          ARG.  The only flags that can be changed are `O_APPEND' and
          `O_NONBLOCK'.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [ERR, MSG] = kill (PID, SIG)
     Send signal SIG to process PID.

     If PID is positive, then signal SIG is sent to PID.

     If PID is 0, then signal SIG is sent to every process in the
     process group of the current process.

     If PID is -1, then signal SIG is sent to every process except
     process 1.

     If PID is less than -1, then signal SIG is sent to every process
     in the process group -PID.

     If SIG is 0, then no signal is sent, but error checking is still
     performed.

     Return 0 if successful, otherwise return -1.

 -- Built-in Function:  SIG ()
     Return a structure containing Unix signal names and their defined
     values.


File: octave.info,  Node: Process ID Information,  Next: Environment Variables,  Prev: Controlling Subprocesses,  Up: System Utilities

36.6 Process, Group, and User IDs
=================================

 -- Built-in Function: pgid = getpgrp ()
     Return the process group id of the current process.

 -- Built-in Function: pid = getpid ()
     Return the process id of the current process.

 -- Built-in Function: pid = getppid ()
     Return the process id of the parent process.

 -- Built-in Function: euid = geteuid ()
     Return the effective user id of the current process.

 -- Built-in Function: uid = getuid ()
     Return the real user id of the current process.

 -- Built-in Function: egid = getegid ()
     Return the effective group id of the current process.

 -- Built-in Function: gid = getgid ()
     Return the real group id of the current process.


File: octave.info,  Node: Environment Variables,  Next: Current Working Directory,  Prev: Process ID Information,  Up: System Utilities

36.7 Environment Variables
==========================

 -- Built-in Function:  getenv (VAR)
     Return the value of the environment variable VAR.  For example,

          getenv ("PATH")

     returns a string containing the value of your path.

 -- Built-in Function:  putenv (VAR, VALUE)
 -- Built-in Function:  setenv (VAR, VALUE)
     Set the value of the environment variable VAR to VALUE.


File: octave.info,  Node: Current Working Directory,  Next: Password Database Functions,  Prev: Environment Variables,  Up: System Utilities

36.8 Current Working Directory
==============================

 -- Command:  cd dir
 -- Command:  chdir dir
     Change the current working directory to DIR.  If DIR is omitted,
     the current directory is changed to the user's home directory.
     For example,

          cd ~/octave

     changes the current working directory to `~/octave'.  If the
     directory does not exist, an error message is printed and the
     working directory is not changed.

     *See also:* *note mkdir: doc-mkdir, *note rmdir: doc-rmdir, *note
     dir: doc-dir.

 -- Command:  ls options
     List directory contents.  For example:

          ls -l
               -| total 12
               -| -rw-r--r--   1 jwe  users  4488 Aug 19 04:02 foo.m
               -| -rw-r--r--   1 jwe  users  1315 Aug 17 23:14 bar.m

     The `dir' and `ls' commands are implemented by calling your
     system's directory listing command, so the available options may
     vary from system to system.

     *See also:* *note dir: doc-dir, *note stat: doc-stat, *note
     readdir: doc-readdir, *note glob: doc-glob, *note filesep:
     doc-filesep, *note ls_command: doc-ls_command.

 -- Function File: VAL = ls_command ()
 -- Function File: OLD_VAL = ls_command (NEW_VAL)
     Query or set the shell command used by Octave's `ls' command.

     *See also:* *note ls: doc-ls.

 -- Function File:  dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.  If a return value
     is requested, return a structure array with the fields

          name
          bytes
          date
          isdir
          statinfo

     where `statinfo' is the structure returned from `stat'.

     If DIRECTORY is not a directory, return information about the
     named FILENAME.  DIRECTORY may be a list of directories specified
     either by name or with wildcard characters (like * and ?)  which
     will be expanded with glob.

     Note that for symbolic links, `dir' returns information about the
     file that the symbolic link points to instead of the link itself.
     However, if the link points to a nonexistent file, `dir' returns
     information about the link.

     *See also:* *note ls: doc-ls, *note stat: doc-stat, *note lstat:
     doc-lstat, *note readdir: doc-readdir, *note glob: doc-glob, *note
     filesep: doc-filesep.

 -- Built-in Function:  pwd ()
     Return the current working directory.

     *See also:* *note dir: doc-dir, *note ls: doc-ls.


File: octave.info,  Node: Password Database Functions,  Next: Group Database Functions,  Prev: Current Working Directory,  Up: System Utilities

36.9 Password Database Functions
================================

Octave's password database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`uid'
     The numeric user id.

`gid'
     The numeric group id.

`gecos'
     The GECOS field.

`dir'
     The home directory.

`shell'
     The initial shell.

   In the descriptions of the following functions, this data structure
is referred to as a PW_STRUCT.

 -- Loadable Function: PW_STRUCT = getpwent ()
     Return a structure containing an entry from the password database,
     opening it if necessary.  Once the end of the data has been
     reached, `getpwent' returns 0.

 -- Loadable Function: PW_STRUCT = getpwuid (UID).
     Return a structure containing the first entry from the password
     database with the user ID UID.  If the user ID does not exist in
     the database, `getpwuid' returns 0.

 -- Loadable Function: PW_STRUCT = getpwnam (NAME)
     Return a structure containing the first entry from the password
     database with the user name NAME.  If the user name does not exist
     in the database, `getpwname' returns 0.

 -- Loadable Function:  setpwent ()
     Return the internal pointer to the beginning of the password
     database.

 -- Loadable Function:  endpwent ()
     Close the password database.


File: octave.info,  Node: Group Database Functions,  Next: System Information,  Prev: Password Database Functions,  Up: System Utilities

36.10 Group Database Functions
==============================

Octave's group database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`gid'
     The numeric group id.

`mem'
     The members of the group.

   In the descriptions of the following functions, this data structure
is referred to as a GRP_STRUCT.

 -- Loadable Function: GRP_STRUCT = getgrent ()
     Return an entry from the group database, opening it if necessary.
     Once the end of data has been reached, `getgrent' returns 0.

 -- Loadable Function: GRP_STRUCT = getgrgid (GID).
     Return the first entry from the group database with the group ID
     GID.  If the group ID does not exist in the database, `getgrgid'
     returns 0.

 -- Loadable Function: GRP_STRUCT = getgrnam (NAME)
     Return the first entry from the group database with the group name
     NAME.  If the group name does not exist in the database,
     `getgrnam' returns 0.

 -- Loadable Function:  setgrent ()
     Return the internal pointer to the beginning of the group database.

 -- Loadable Function:  endgrent ()
     Close the group database.


File: octave.info,  Node: System Information,  Next: Hashing Functions,  Prev: Group Database Functions,  Up: System Utilities

36.11 System Information
========================

 -- Function File: [C, MAXSIZE, ENDIAN] = computer ()
 -- Function File: ARCH = computer ("arch")
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the kind of computer Octave is running on.  If invoked with an
     output argument, the value is returned instead of printed.  For
     example:

          computer ()
             -| i586-pc-linux-gnu

          x = computer ()
             => x = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.

     If three output arguments are requested, also return the byte order
     of the current system as a character (`"B"' for big-endian or
     `"L"' for little-endian).

     If the argument `"arch"' is specified, return a string indicating
     the architecture of the computer on which Octave is running.

 -- Built-in Function: [UTS, ERR, MSG] = uname ()
     Return system information in the structure.  For example:

          uname ()
               => {
                     sysname = x86_64
                     nodename = segfault
                     release = 2.6.15-1-amd64-k8-smp
                     version = Linux
                     machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006
                   }

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Loadable Function:  nproc ()
 -- Loadable Function:  nproc (QUERY)
     Return the current number of available processors.

     If called with the optional argument QUERY, modify how processors
     are counted as follows:
    `all'
          total number of processors.

    `current'
          processors available to the current process.

    `overridable'
          likewise, but overridable through the `OMP_NUM_THREADS'
          environment variable.

 -- Function File:  ispc ()
     Return true if Octave is running on a Windows system and false
     otherwise.

     *See also:* *note isunix: doc-isunix, *note ismac: doc-ismac.

 -- Function File:  isunix ()
     Return true if Octave is running on a Unix-like system and false
     otherwise.

     *See also:* *note ismac: doc-ismac, *note ispc: doc-ispc.

 -- Function File:  ismac ()
     Return true if Octave is running on a Mac OS X system and false
     otherwise.

     *See also:* *note isunix: doc-isunix, *note ispc: doc-ispc.

 -- Built-in Function:  isieee ()
     Return true if your computer _claims_ to conform to the IEEE
     standard for floating point calculations.  No actual tests are
     performed.

 -- Function File:  isdeployed ()
     Return true if the current program has been compiled and is running
     separately from the Octave interpreter and false if it is running
     in the Octave interpreter.  Currently, this function always returns
     false in Octave.

 -- Built-in Function:  OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory.

 -- Function File:  matlabroot ()
     Return the name of the top-level Octave installation directory.

     This is an alias for the function `OCTAVE_HOME' provided for
     compatibility.

     *See also:* *note OCTAVE_HOME: doc-OCTAVE_HOME.

 -- Built-in Function:  OCTAVE_VERSION ()
     Return the version number of Octave, as a string.

 -- Function File:  version ()
     Return the version number of Octave, as a string.

     This is an alias for the function `OCTAVE_VERSION' provided for
     compatibility

     *See also:* *note OCTAVE_VERSION: doc-OCTAVE_VERSION..

 -- Function File:  ver ()
     Display a header containing the current Octave version number,
     license string and operating system, followed by the installed
     package names, versions, and installation directories.

 -- Function File: v = ver ()
     Return a vector of structures, respecting Octave and each
     installed package.  The structure includes the following fields.

    `Name'
          Package name.

    `Version'
          Version of the package.

    `Revision'
          Revision of the package.

    `Date'
          Date respecting the version/revision.

 -- Function File: v = ver ("Octave")
     Return version information for Octave only.

 -- Function File: v = ver (PACKAGE)
     Return version information for PACKAGE.

     *See also:* *note version: doc-version, *note octave_config_info:
     doc-octave_config_info.

 -- Function File:  compare_versions (V1, V2, OPERATOR)
     Compare two version strings using the given OPERATOR.

     This function assumes that versions V1 and V2 are arbitrarily long
     strings made of numeric and period characters possibly followed by
     an arbitrary string (e.g., "1.2.3", "0.3", "0.1.2+", or
     "1.2.3.4-test1").

     The version is first split into numeric and character portions and
     then the parts are padded to be the same length (i.e., "1.1" would
     be padded to be "1.1.0" when being compared with "1.1.1", and
     separately, the character parts of the strings are padded with
     nulls).

     The operator can be any logical operator from the set

        * "==" equal

        * "<" less than

        * "<=" less than or equal to

        * ">" greater than

        * ">=" greater than or equal to

        * "!=" not equal

        * "~=" not equal

     Note that version "1.1-test2" will compare as greater than
     "1.1-test10".  Also, since the numeric part is compared first, "a"
     compares less than "1a" because the second string starts with a
     numeric part even though `double("a")' is greater than
     `double("1").'

 -- Function File:  license
     Display the license of Octave.

 -- Function File:  license ("inuse")
     Display a list of packages currently being used.

 -- Function File: RETVAL = license ("inuse")
     Return a structure containing the fields `feature' and `user'.

 -- Function File: RETVAL = license ("test", FEATURE)
     Return 1 if a license exists for the product identified by the
     string FEATURE and 0 otherwise.  The argument FEATURE is case
     insensitive and only the first 27 characters are checked.

 -- Function File:  license ("test", FEATURE, TOGGLE)
     Enable or disable license testing for FEATURE, depending on
     TOGGLE, which may be one of:

    "enable"
          Future tests for the specified license of FEATURE are
          conducted as usual.

    "disable"
          Future tests for the specified license of FEATURE return 0.

 -- Function File: RETVAL = license ("checkout", FEATURE)
     Check out a license for FEATURE, returning 1 on success and 0 on
     failure.

     This function is provided for compatibility with MATLAB.

     *See also:* *note ver: doc-ver, *note version: doc-version.

 -- Built-in Function:  octave_config_info ()
 -- Built-in Function:  octave_config_info (OPTION)
     Return a structure containing configuration and installation
     information for Octave.

     If OPTION is a string, return the configuration information for the
     specified option.


 -- Function File:  usejava (FEATURE)
     Return true if the specific Sun Java element FEATURE is available.

     Possible features are:

    "awt"
          Abstract Window Toolkit for GUIs.

    "desktop"
          Interactive desktop is running.

    "jvm"
          Java Virtual Machine.

    "swing"
          Swing components for lightweight GUIs.

     This function is provided for compatibility with MATLAB scripts
     which may alter their behavior based on the availability of Java.
     Octave does not implement an interface to Java and this function
     always returns `false'.

 -- Loadable Function:  getrusage ()
     Return a structure containing a number of statistics about the
     current Octave process.  Not all fields are available on all
     systems.  If it is not possible to get CPU time statistics, the
     CPU time slots are set to zero.  Other missing data are replaced
     by NaN.  The list of possible fields is:

    `idrss'
          Unshared data size.

    `inblock'
          Number of block input operations.

    `isrss'
          Unshared stack size.

    `ixrss'
          Shared memory size.

    `majflt'
          Number of major page faults.

    `maxrss'
          Maximum data size.

    `minflt'
          Number of minor page faults.

    `msgrcv'
          Number of messages received.

    `msgsnd'
          Number of messages sent.

    `nivcsw'
          Number of involuntary context switches.

    `nsignals'
          Number of signals received.

    `nswap'
          Number of swaps.

    `nvcsw'
          Number of voluntary context switches.

    `oublock'
          Number of block output operations.

    `stime'
          A structure containing the system CPU time used.  The
          structure has the elements `sec' (seconds) `usec'
          (microseconds).

    `utime'
          A structure containing the user CPU time used.  The structure
          has the elements `sec' (seconds) `usec' (microseconds).

