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

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

@node Statistics
@chapter Statistics

Octave has support for various statistical methods.  The emphasis is on basic
descriptive statistics, but the Octave Forge statistics package includes
probability distributions, statistical tests, random number generation, and
much more.

The functions that analyze data all assume that multi-dimensional data is
arranged in a matrix where each row is an observation, and each column is a
variable.  Thus, the matrix defined by

@example
@group
a = [ 0.9, 0.7;
      0.1, 0.1;
      0.5, 0.4 ];
@end group
@end example

@noindent
contains three observations from a two-dimensional distribution.  While this is
the default data arrangement, most functions support different arrangements.

It should be noted that the statistics functions don't test for data containing
NaN, NA, or Inf.  These values need to be detected and dealt with explicitly.
See @ref{XREFisnan,,isnan}, @ref{XREFisna,,isna}, @ref{XREFisinf,,isinf},
@ref{XREFisfinite,,isfinite}.

@menu
* Descriptive Statistics::
* Statistics on Sliding Windows of Data::
* Basic Statistical Functions::
* Correlation and Regression Analysis::
* Distributions::
* Random Number Generation::
@end menu

@node Descriptive Statistics
@section Descriptive Statistics

One principal goal of descriptive statistics is to represent the essence of a
large data set concisely.  Octave provides the mean, median, and mode functions
which all summarize a data set with just a single number corresponding to
the central tendency of the data.

@c mean scripts/statistics/mean.m
@anchor{XREFmean}
@deftypefn  {} {@var{y} =} mean (@var{x})
@deftypefnx {} {@var{y} =} mean (@var{x}, 'all')
@deftypefnx {} {@var{y} =} mean (@var{x}, @var{dim})
@deftypefnx {} {@var{y} =} mean (@dots{}, '@var{outtype}')
@deftypefnx {} {@var{y} =} mean (@dots{}, '@var{nanflag}')
Compute the mean of the elements of @var{x}.

@itemize
@item
If @var{x} is a vector, then @code{mean (@var{x})} returns the
mean of the elements in @var{x} defined as
@tex
$$ {\rm mean}(x) = \bar{x} = {1\over N} \sum_{i=1}^N x_i $$
where $N$ is the number of elements of @var{x}.

@end tex
@ifnottex

@example
mean (@var{x}) = SUM_i @var{x}(i) / N
@end example

@noindent
where @math{N} is the number of elements in the @var{x} vector.

@end ifnottex

@item
If @var{x} is a matrix, then @code{mean} returns a row vector with the mean
of each column in @var{x}.

@item
If @var{x} is a multi-dimensional array, then @code{mean} operates along the
first non-singleton dimension of @var{x}.
@end itemize

The optional input @var{dim} forces @code{mean} to operate over the
specified dimension(s).  @var{dim} can either be a scalar dimension or a
vector of non-repeating dimensions.  Dimensions must be positive integers,
and the mean is calculated over the array slice defined by @var{dim}.

Specifying dimension @qcode{"all"} will force @code{mean} to operate on all
elements of @var{x}, and is equivalent to @code{mean (@var{x}(:))}.

The optional input @var{outtype} specifies the data type that is returned.
Valid values are:

@table @asis
@item @qcode{'default'} : Output is of type double, unless the input is
single in which case the output is of type single.

@item @qcode{'double'} : Output is of type double.

@item @qcode{'native'} : Output is of the same type as the input
(@code{class (@var{x})}), unless the input is logical in which case the
output is of type double.

@end table

The optional input @var{nanflag} specifies whether to include/exclude NaN
values from the calculation.  By default, NaN values are included in the
calculation (@var{nanflag} has the value @qcode{'includenan'}).  To exclude
NaN values, set the value of @var{nanflag} to @qcode{'omitnan'}.

@xseealso{@ref{XREFmedian,,median}, @ref{XREFmode,,mode}}
@end deftypefn


@c median scripts/statistics/median.m
@anchor{XREFmedian}
@deftypefn  {} {@var{y} =} median (@var{x})
@deftypefnx {} {@var{y} =} median (@var{x}, @var{dim})
Compute the median value of the elements of the vector @var{x}.

When the elements of @var{x} are sorted, say
@code{@var{s} = sort (@var{x})}, the median is defined as
@tex
$$
{\rm median} (x) =
  \cases{s(\lceil N/2\rceil), & $N$ odd;\cr
          (s(N/2)+s(N/2+1))/2, & $N$ even.}
$$
where $N$ is the number of elements of @var{x}.

@end tex
@ifnottex

@example
@group
             |  @var{s}(ceil(N/2))           N odd
median (@var{x}) = |
             | (@var{s}(N/2) + @var{s}(N/2+1))/2   N even
@end group
@end example

@end ifnottex
If @var{x} is of a discrete type such as integer or logical, then
the case of even @math{N} rounds up (or toward @code{true}).

If @var{x} is a matrix, compute the median value for each column and
return them in a row vector.

If the optional @var{dim} argument is given, operate along this dimension.
@xseealso{@ref{XREFmean,,mean}, @ref{XREFmode,,mode}}
@end deftypefn


@c mode scripts/statistics/mode.m
@anchor{XREFmode}
@deftypefn  {} {@var{m} =} mode (@var{x})
@deftypefnx {} {@var{m} =} mode (@var{x}, @var{dim})
@deftypefnx {} {[@var{m}, @var{f}, @var{c}] =} mode (@dots{})
Compute the most frequently occurring value in a dataset (mode).

@code{mode} determines the frequency of values along the first non-singleton
dimension and returns the value with the highest frequency.  If two, or
more, values have the same frequency @code{mode} returns the smallest.

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

The return variable @var{f} is the number of occurrences of the mode in
the dataset.

The cell array @var{c} contains all of the elements with the maximum
frequency.
@xseealso{@ref{XREFmean,,mean}, @ref{XREFmedian,,median}}
@end deftypefn


Using just one number, such as the mean, to represent an entire data set may
not give an accurate picture of the data.  One way to characterize the fit is
to measure the dispersion of the data.  Octave provides several functions for
measuring dispersion.

@c bounds scripts/statistics/bounds.m
@anchor{XREFbounds}
@deftypefn  {} {[@var{s}, @var{l}] =} bounds (@var{x})
@deftypefnx {} {[@var{s}, @var{l}] =} bounds (@var{x}, @var{dim})
@deftypefnx {} {[@var{s}, @var{l}] =} bounds (@dots{}, "nanflag")
Return the smallest and largest values of the input data @var{x}.

If @var{x} is a vector, the bounds are calculated over the elements of
@var{x}.  If @var{x} is a matrix, the bounds are calculated for each column.
For a multi-dimensional array, the bounds are calculated over the first
non-singleton dimension.

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

The optional argument @qcode{"nanflag"} defaults to @qcode{"omitnan"} which
does not include NaN values in the result.  If the argument
@qcode{"includenan"} is given, and there is a NaN present, then the result
for both smallest (@var{s}) and largest (@var{l}) elements will be NaN.

The bounds are a quickly computed measure of the dispersion of a data set,
but are less accurate than @code{iqr} if there are outlying data points.
@xseealso{@ref{XREFrange,,range}, @ref{XREFiqr,,iqr}, @ref{XREFmad,,mad}, @ref{XREFstd,,std}}
@end deftypefn


@c range scripts/statistics/range.m
@anchor{XREFrange}
@deftypefn  {} {@var{y} =} range (@var{x})
@deftypefnx {} {@var{y} =} range (@var{x}, @var{dim})
Return the range, i.e., the difference between the maximum and the minimum
of the input data.

If @var{x} is a vector, the range is calculated over the elements of
@var{x}.  If @var{x} is a matrix, the range is calculated over each column
of @var{x}.

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

The range is a quickly computed measure of the dispersion of a data set, but
is less accurate than @code{iqr} if there are outlying data points.
@xseealso{@ref{XREFbounds,,bounds}, @ref{XREFiqr,,iqr}, @ref{XREFmad,,mad}, @ref{XREFstd,,std}}
@end deftypefn


@c iqr scripts/statistics/iqr.m
@anchor{XREFiqr}
@deftypefn  {} {@var{Z} =} iqr (@var{x})
@deftypefnx {} {@var{Z} =} iqr (@var{x}, @var{dim})
@deftypefnx {} {@var{Z} =} iqr (@var{x}, @qcode{"ALL"})
Return the interquartile range of @var{x}, defined as the distance between
the 25th and 75th percentile values of @var{x} calculated using:
   quantile (x, [0.25 0.75])

If @var{x} is a vector, @code{iqr (@var{x})} will operate on the data in
@var{x}.

If @var{x} is a matrix, @code{iqr (@var{x})} will operate independently on
each column in @var{x} returning a row vector @var{Z}.

If @var{x} is a n-dimensional array, @code{iqr (@var{x})} will operate
independently on the first non-singleton dimension in @var{x}, returning an
array @var{Z} the same shape as @var{x} with the non-singleton dimenion
reduced to 1.

The optional variable @var{dim} can be used to force @code{iqr} to operate
over the specified dimension.  @var{dim} can either be a scalar dimension or
a vector of non-repeating dimensions over which to operate.  In either case
@var{dim} must be positive integers.  A vector @var{dim} concatenates all
specified dimensions for independent operation by @code{iqr}.

Specifying dimension @qcode{"ALL"} will force @code{iqr} to operate
on all elements of @var{x}, and is equivalent to @code{iqr (@var{x}(:))}.
Similarly, specifying a vector dimension including all non-singleton
dimensions of @var{x} is equivalent to @code{iqr (@var{x}, @qcode{"ALL"})}.

If @var{x} is a scalar, or only singleton dimensions are specified for
@var{dim}, the output will be @code{zeros (size (@var{x}))}.

As a measure of dispersion, the interquartile range is less affected by
outliers than either @code{range} or @code{std}.

@xseealso{@ref{XREFbounds,,bounds}, @ref{XREFmad,,mad}, @ref{XREFrange,,range}, @ref{XREFstd,,std}, @ref{XREFprctile,,prctile}, @ref{XREFquantile,,quantile}}
@end deftypefn


@c mad scripts/statistics/mad.m
@anchor{XREFmad}
@deftypefn  {} {@var{y} =} mad (@var{x})
@deftypefnx {} {@var{y} =} mad (@var{x}, @var{opt})
@deftypefnx {} {@var{y} =} mad (@var{x}, @var{opt}, @var{dim})
Compute the mean or median absolute deviation of the elements of @var{x}.

The mean absolute deviation is defined as

@example
@var{mad} = mean (abs (@var{x} - mean (@var{x})))
@end example

The median absolute deviation is defined as

@example
@var{mad} = median (abs (@var{x} - median (@var{x})))
@end example

If @var{x} is a matrix, compute @code{mad} for each column and return
results in a row vector.  For a multi-dimensional array, the calculation is
done over the first non-singleton dimension.

The optional argument @var{opt} determines whether mean or median absolute
deviation is calculated.  The default is 0 which corresponds to mean
absolute deviation; A value of 1 corresponds to median absolute deviation.

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

As a measure of dispersion, @code{mad} is less affected by outliers than
@code{std}.
@xseealso{@ref{XREFbounds,,bounds}, @ref{XREFrange,,range}, @ref{XREFiqr,,iqr}, @ref{XREFstd,,std}, @ref{XREFmean,,mean}, @ref{XREFmedian,,median}}
@end deftypefn


@c meansq scripts/statistics/meansq.m
@anchor{XREFmeansq}
@deftypefn  {} {@var{y} =} meansq (@var{x})
@deftypefnx {} {@var{y} =} meansq (@var{x}, @var{dim})
Compute the mean square of the elements of the vector @var{x}.

The mean square is defined as
@tex
$$
{\rm meansq} (x) = {\sum_{i=1}^N {x_i}^2 \over N}
$$
where $N$ is the number of elements of @var{x}.

@end tex
@ifnottex

@example
@group
meansq (@var{x}) = 1/N SUM_i @var{x}(i)^2
@end group
@end example

@noindent
where @math{N} is the length of the @var{x} vector.

@end ifnottex
If @var{x} is a matrix, return a row vector containing the mean square
of each column.

If the optional argument @var{dim} is given, operate along this dimension.
@xseealso{@ref{XREFvar,,var}, @ref{XREFstd,,std}, @ref{XREFmoment,,moment}}
@end deftypefn


@c std scripts/statistics/std.m
@anchor{XREFstd}
@deftypefn  {} {@var{y} =} std (@var{x})
@deftypefnx {} {@var{y} =} std (@var{x}, @var{w})
@deftypefnx {} {@var{y} =} std (@var{x}, @var{w}, @var{dim})
@deftypefnx {} {@var{y} =} std (@var{x}, @var{w}, @qcode{"ALL"})
@deftypefnx {} {[@var{y}, @var{mu}] =} std (@dots{})
Compute the standard deviation of the elements of the vector @var{x}.

The standard deviation is defined as
@tex
$$
{\rm std} (x) = \sigma = \sqrt{{\sum_{i=1}^N (x_i - \bar{x})^2 \over N - 1}}
$$
where $\bar{x}$ is the mean value of @var{x} and $N$ is the number of elements of @var{x}.
@end tex
@ifnottex

@example
@group
std (@var{x}) = sqrt ( 1/(N-1) SUM_i (@var{x}(i) - mean(@var{x}))^2 )
@end group
@end example

@noindent
where @math{N} is the number of elements of the @var{x} vector.
@end ifnottex

If @var{x} is an array, compute the standard deviation for each column and
return them in a row vector (or for an n-D array, the result is returned as
an array of dimension 1 x n x m x @dots{}).

The optional argument @var{w} determines the weighting scheme to use.  Valid
values are:

@table @asis
@item 0 [default]:
Normalize with @math{N-1}.  This provides the square root of the best
unbiased estimator of the variance.

@item 1:
Normalize with @math{N}@.  This provides the square root of the second
moment around the mean.

@item a vector:
Compute the weighted standard deviation with non-negative scalar weights.
The length of @var{w} must equal the size of @var{x} along dimension
@var{dim}.
@end table

If @math{N} is equal to 1 the value of @var{W} is ignored and normalization
by @math{N} is used.

The optional variable @var{dim} forces @code{std} to operate over the
specified dimension(s).  @var{dim} can either be a scalar dimension or a
vector of non-repeating dimensions.  Dimensions must be positive integers,
and the standard deviation is calculated over the array slice defined by
@var{dim}.

Specifying dimension @qcode{"all"} will force @code{std} to operate on all
elements of @var{x}, and is equivalent to @code{std (@var{x}(:))}.

When @var{dim} is a vector or @qcode{"all"}, @var{w} must be either 0 or 1.

The optional second output variable @var{mu} contains the mean or weighted
mean used to calculate @var{y}, and will be the same size as @var{y}.
@xseealso{@ref{XREFvar,,var}, @ref{XREFbounds,,bounds}, @ref{XREFmad,,mad}, @ref{XREFrange,,range}, @ref{XREFiqr,,iqr}, @ref{XREFmean,,mean}, @ref{XREFmedian,,median}}
@end deftypefn


In addition to knowing the size of a dispersion it is useful to know the shape
of the data set.  For example, are data points massed to the left or right
of the mean?  Octave provides several common measures to describe the shape
of the data set.  Octave can also calculate moments allowing arbitrary shape
measures to be developed.

@c var scripts/statistics/var.m
@anchor{XREFvar}
@deftypefn  {} {@var{v} =} var (@var{x})
@deftypefnx {} {@var{v} =} var (@var{x}, @var{w})
@deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @var{dim})
@deftypefnx {} {@var{v} =} var (@var{x}, @var{w}, @qcode{"ALL"})
@deftypefnx {} {[@var{v}, @var{m}] =} var (@dots{})
Compute the variance of the elements of the vector @var{x}.

The variance is defined as
@tex
$$
{\rm var} (x) = \sigma^2 = {\sum_{i=1}^N (x_i - \bar{x})^2 \over N - 1}
$$
where $\bar{x}$ is the mean value of @var{x} and $N$ is the number of
elements of @var{x}.

@end tex
@ifnottex

@example
@group
var (@var{x}) = 1/(N-1) SUM_i (@var{x}(i) - mean(@var{x}))^2
@end group
@end example

@noindent
where @math{N} is the length of the @var{x} vector.

@end ifnottex
If @var{x} is an array, compute the variance for each column and return them
in a row vector (or for an n-D array, the result is returned as an array of
dimension 1 x n x m x @dots{}).

The optional argument @var{w} determines the weighting scheme to use.  Valid
values are

@table @asis
@item 0 [default]:
Normalize with @math{N-1}.  This provides the square root of the best
unbiased estimator of the variance.

@item 1:
Normalize with @math{N}@.  This provides the square root of the second
moment around the mean.

@item a vector:
Compute the weighted variance with non-negative scalar weights.  The length
of @var{w} must equal the size of @var{x} along dimension @var{dim}.
@end table

If @math{N} is equal to 1 the value of @var{W} is ignored and normalization
by @math{N} is used.

The optional variable @var{dim} forces @code{var} to operate over the
specified dimension(s).  @var{dim} can either be a scalar dimension or a
vector of non-repeating dimensions.  Dimensions must be positive integers,
and the variance is calculated over the array slice defined by @var{dim}.

Specifying dimension @qcode{"all"} will force @code{var} to operate on all
elements of @var{x}, and is equivalent to @code{var (@var{x}(:))}.

When @var{dim} is a vector or @qcode{"all"}, @var{w} must be either 0 or 1.

The optional second output variable @var{mu} contains the mean or weighted
mean used to calculate @var{v}, and will be the same size as @var{v}.
@xseealso{@ref{XREFcov,,cov}, @ref{XREFstd,,std}, @ref{XREFskewness,,skewness}, @ref{XREFkurtosis,,kurtosis}, @ref{XREFmoment,,moment}}
@end deftypefn


@c skewness scripts/statistics/skewness.m
@anchor{XREFskewness}
@deftypefn  {} {@var{y} =} skewness (@var{x})
@deftypefnx {} {@var{y} =} skewness (@var{x}, @var{flag})
@deftypefnx {} {@var{y} =} skewness (@var{x}, @var{flag}, @var{dim})
Compute the sample skewness of the elements of @var{x}.

The sample skewness is defined as
@tex
$$
{\rm skewness} (@var{x}) = {{{1\over N}\,
         \sum_{i=1}^N (x_i - \bar{x})^3} \over \sigma^3},
$$
where $N$ is the length of @var{x}, $\bar{x}$ its mean and $\sigma$
its (uncorrected) standard deviation.
@end tex
@ifnottex

@example
@group
               mean ((@var{x} - mean (@var{x})).^3)
skewness (@var{X}) = ------------------------.
                      std (@var{x}).^3
@end group
@end example

@end ifnottex

@noindent
The optional argument @var{flag} controls which normalization is used.
If @var{flag} is equal to 1 (default value, used when @var{flag} is omitted
or empty), return the sample skewness as defined above.  If @var{flag} is
equal to 0, return the adjusted skewness coefficient instead:
@tex
$$
{\rm skewness} (@var{x}) = {\sqrt{N (N - 1)} \over N - 2} \times \,
  {{{1 \over N} \sum_{i=1}^N (x_i - \bar{x})^3} \over \sigma^3}
$$
@end tex
@ifnottex

@example
@group
                  sqrt (N*(N-1))   mean ((@var{x} - mean (@var{x})).^3)
skewness (@var{X}, 0) = -------------- * ------------------------.
                      (N - 2)             std (@var{x}).^3
@end group
@end example

@noindent
where @math{N} is the length of the @var{x} vector.

@end ifnottex
The adjusted skewness coefficient is obtained by replacing the sample second
and third central moments by their bias-corrected versions.

If @var{x} is a matrix, or more generally a multi-dimensional array, return
the skewness along the first non-singleton dimension.  If the optional
@var{dim} argument is given, operate along this dimension.

@xseealso{@ref{XREFvar,,var}, @ref{XREFkurtosis,,kurtosis}, @ref{XREFmoment,,moment}}
@end deftypefn


@c kurtosis scripts/statistics/kurtosis.m
@anchor{XREFkurtosis}
@deftypefn  {} {@var{y} =} kurtosis (@var{x})
@deftypefnx {} {@var{y} =} kurtosis (@var{x}, @var{flag})
@deftypefnx {} {@var{y} =} kurtosis (@var{x}, @var{flag}, @var{dim})
Compute the sample kurtosis of the elements of @var{x}.

The sample kurtosis is defined as
@tex
$$
\kappa_1 = {{{1\over N}\,
         \sum_{i=1}^N (x_i - \bar{x})^4} \over \sigma^4},
$$
where $N$ is the length of @var{x}, $\bar{x}$ its mean, and $\sigma$
its (uncorrected) standard deviation.
@end tex
@ifnottex

@example
@group
     mean ((@var{x} - mean (@var{x})).^4)
k1 = ------------------------
            std (@var{x}).^4
@end group
@end example

@end ifnottex

@noindent
The optional argument @var{flag} controls which normalization is used.
If @var{flag} is equal to 1 (default value, used when @var{flag} is omitted
or empty), return the sample kurtosis as defined above.  If @var{flag} is
equal to 0, return the @w{"bias-corrected"} kurtosis coefficient instead:
@tex
$$
\kappa_0 = 3 + {\scriptstyle N - 1 \over \scriptstyle (N - 2)(N - 3)} \,
    \left( (N + 1)\, \kappa_1 - 3 (N - 1) \right)
$$
@end tex
@ifnottex

@example
@group
              N - 1
k0 = 3 + -------------- * ((N + 1) * k1 - 3 * (N - 1))
         (N - 2)(N - 3)
@end group
@end example

@noindent
where @math{N} is the length of the @var{x} vector.

@end ifnottex
The bias-corrected kurtosis coefficient is obtained by replacing the sample
second and fourth central moments by their unbiased versions.  It is an
unbiased estimate of the population kurtosis for normal populations.

If @var{x} is a matrix, or more generally a multi-dimensional array, return
the kurtosis along the first non-singleton dimension.  If the optional
@var{dim} argument is given, operate along this dimension.

@xseealso{@ref{XREFvar,,var}, @ref{XREFskewness,,skewness}, @ref{XREFmoment,,moment}}
@end deftypefn


@c moment scripts/statistics/moment.m
@anchor{XREFmoment}
@deftypefn  {} {@var{m} =} moment (@var{x}, @var{p})
@deftypefnx {} {@var{m} =} moment (@var{x}, @var{p}, @var{type})
@deftypefnx {} {@var{m} =} moment (@var{x}, @var{p}, @var{dim})
@deftypefnx {} {@var{m} =} moment (@var{x}, @var{p}, @var{type}, @var{dim})
@deftypefnx {} {@var{m} =} moment (@var{x}, @var{p}, @var{dim}, @var{type})
Compute the @var{p}-th central moment of the vector @var{x}.

The @var{p}-th central moment of @var{x} is defined as:

@tex
$$
{\sum_{i=1}^N (x_i - \bar{x})^p \over N}
$$
where $\bar{x}$ is the mean value of @var{x} and $N$ is the number of elements of @var{x}.


@end tex
@ifnottex

@example
@group
1/N SUM_i (@var{x}(i) - mean(@var{x}))^@var{p}
@end group
@end example

@noindent
where @math{N} is the length of the @var{x} vector.

@end ifnottex

If @var{x} is a matrix, return the row vector containing the @var{p}-th
central moment of each column.

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

The optional string @var{type} specifies the type of moment to be computed.
Valid options are:

@table @asis
@item @qcode{"c"}
  Central Moment (default).

@item  @qcode{"a"}
@itemx @qcode{"ac"}
  Absolute Central Moment.  The moment about the mean ignoring sign
defined as
@tex
$$
{\sum_{i=1}^N {\left| x_i - \bar{x} \right|}^p \over N}
$$
@end tex
@ifnottex

@example
@group
1/N SUM_i (abs (@var{x}(i) - mean(@var{x})))^@var{p}
@end group
@end example

@end ifnottex

@item @qcode{"r"}
  Raw Moment.  The moment about zero defined as

@tex
$$
{\rm moment} (x) = { \sum_{i=1}^N {x_i}^p \over N }
$$
@end tex
@ifnottex

@example
@group
moment (@var{x}) = 1/N SUM_i @var{x}(i)^@var{p}
@end group
@end example

@end ifnottex

@item @nospell{@qcode{"ar"}}
  Absolute Raw Moment.  The moment about zero ignoring sign defined as
@tex
$$
{\sum_{i=1}^N {\left| x_i \right|}^p \over N}
$$
@end tex
@ifnottex

@example
@group
1/N SUM_i ( abs (@var{x}(i)) )^@var{p}
@end group
@end example

@end ifnottex
@end table

If both @var{type} and @var{dim} are given they may appear in any order.
@xseealso{@ref{XREFvar,,var}, @ref{XREFskewness,,skewness}, @ref{XREFkurtosis,,kurtosis}}
@end deftypefn


@c quantile scripts/statistics/quantile.m
@anchor{XREFquantile}
@deftypefn  {} {@var{q} =} quantile (@var{x})
@deftypefnx {} {@var{q} =} quantile (@var{x}, @var{p})
@deftypefnx {} {@var{q} =} quantile (@var{x}, @var{p}, @var{dim})
@deftypefnx {} {@var{q} =} quantile (@var{x}, @var{p}, @var{dim}, @var{method})
For a sample, @var{x}, calculate the quantiles, @var{q}, corresponding to
the cumulative probability values in @var{p}.  All non-numeric values (NaNs)
of @var{x} are ignored.

If @var{x} is a matrix, compute the quantiles for each column and
return them in a matrix, such that the i-th row of @var{q} contains
the @var{p}(i)th quantiles of each column of @var{x}.

If @var{p} is unspecified, return the quantiles for
@code{[0.00 0.25 0.50 0.75 1.00]}.
The optional argument @var{dim} determines the dimension along which
the quantiles are calculated.  If @var{dim} is omitted it defaults to
the first non-singleton dimension.

The methods available to calculate sample quantiles are the nine methods
used by R (@url{https://www.r-project.org/}).  The default value is
@w{@var{method} = 5}.

Discontinuous sample quantile methods 1, 2, and 3

@enumerate 1
@item Method 1: Inverse of empirical distribution function.

@item Method 2: Similar to method 1 but with averaging at discontinuities.

@item Method 3: SAS definition: nearest even order statistic.
@end enumerate

Continuous sample quantile methods 4 through 9, where
@tex
$p(k)$
@end tex
@ifnottex
@var{p}(k)
@end ifnottex
is the linear
interpolation function respecting each method's representative cdf.

@enumerate 4
@item Method 4:
@tex
$p(k) = k / N$.
@end tex
@ifnottex
@var{p}(k) = k / N.
@end ifnottex
That is, linear interpolation of the empirical cdf, where @math{N} is the
length of @var{P}.

@item Method 5:
@tex
$p(k) = (k - 0.5) / N$.
@end tex
@ifnottex
@var{p}(k) = (k - 0.5) / N.
@end ifnottex
That is, a piecewise linear function where the knots are the values midway
through the steps of the empirical cdf.

@item Method 6:
@tex
$p(k) = k / (N + 1)$.
@end tex
@ifnottex
@var{p}(k) = k / (N + 1).
@end ifnottex

@item Method 7:
@tex
$p(k) = (k - 1) / (N - 1)$.
@end tex
@ifnottex
@var{p}(k) = (k - 1) / (N - 1).
@end ifnottex

@item Method 8:
@tex
$p(k) = (k - 1/3) / (N + 1/3)$.
@end tex
@ifnottex
@var{p}(k) = (k - 1/3) / (N + 1/3).
@end ifnottex
The resulting quantile estimates are approximately median-unbiased
regardless of the distribution of @var{x}.

@item Method 9:
@tex
$p(k) = (k - 3/8) / (N + 1/4)$.
@end tex
@ifnottex
@var{p}(k) = (k - 3/8) / (N + 1/4).
@end ifnottex
The resulting quantile estimates are approximately unbiased for the
expected order statistics if @var{x} is normally distributed.
@end enumerate

@nospell{Hyndman and Fan} (1996) recommend method 8.  Maxima, S, and R
(versions prior to 2.0.0) use 7 as their default.  Minitab and SPSS
use method 6.  @sc{matlab} uses method 5.

References:

@itemize @bullet
@item @nospell{Becker, R. A., Chambers, J. M. and Wilks, A. R.} (1988)
The New S Language.  @nospell{Wadsworth & Brooks/Cole}.

@item @nospell{Hyndman, R. J. and Fan, Y.} (1996) Sample quantiles in
statistical packages, American Statistician, 50, 361--365.

@item R: A Language and Environment for Statistical Computing;
@url{https://cran.r-project.org/doc/manuals/fullrefman.pdf}.
@end itemize

Examples:
@c Set example in small font to prevent overfull line

@smallexample
@group
x = randi (1000, [10, 1]);  # Create empirical data in range 1-1000
q = quantile (x, [0, 1]);   # Return minimum, maximum of distribution
q = quantile (x, [0.25 0.5 0.75]); # Return quartiles of distribution
@end group
@end smallexample
@xseealso{@ref{XREFprctile,,prctile}}
@end deftypefn


@c prctile scripts/statistics/prctile.m
@anchor{XREFprctile}
@deftypefn  {} {@var{q} =} prctile (@var{x})
@deftypefnx {} {@var{q} =} prctile (@var{x}, @var{p})
@deftypefnx {} {@var{q} =} prctile (@var{x}, @var{p}, @var{dim})
For a sample @var{x}, compute the quantiles, @var{q}, corresponding
to the cumulative probability values, @var{p}, in percent.

If @var{x} is a matrix, compute the percentiles for each column and return
them in a matrix, such that the i-th row of @var{q} contains the
@var{p}(i)th percentiles of each column of @var{x}.

If @var{p} is unspecified, return the quantiles for @code{[0 25 50 75 100]}.

The optional argument @var{dim} determines the dimension along which the
percentiles are calculated.  If @var{dim} is omitted it defaults to the
first non-singleton dimension.

Programming Note: All non-numeric values (NaNs) of @var{x} are ignored.
@xseealso{@ref{XREFquantile,,quantile}}
@end deftypefn


A summary view of a data set can be generated quickly with the
@code{statistics} function.

@c statistics scripts/statistics/statistics.m
@anchor{XREFstatistics}
@deftypefn  {} {@var{stats} =} statistics (@var{x})
@deftypefnx {} {@var{stats} =} statistics (@var{x}, @var{dim})
Return a vector with the minimum, first quartile, median, third quartile,
maximum, mean, standard deviation, skewness, and kurtosis of the elements of
the vector @var{x}.

If @var{x} is a matrix, calculate statistics over the first non-singleton
dimension.

If the optional argument @var{dim} is given, operate along this dimension.
@xseealso{@ref{XREFmin,,min}, @ref{XREFmax,,max}, @ref{XREFmedian,,median}, @ref{XREFmean,,mean}, @ref{XREFstd,,std}, @ref{XREFskewness,,skewness}, @ref{XREFkurtosis,,kurtosis}}
@end deftypefn


@node Statistics on Sliding Windows of Data
@section Statistics on Sliding Windows of Data

It is often useful to calculate descriptive statistics over a subsection
(i.e., window) of a full dataset.  Octave provides the function @code{movfun}
which will call an arbitrary function handle with windows of data and
accumulate the results.  Many of the most commonly desired functions, such as
the moving average over a window of data (@code{movmean}), are already
provided.

@c movfun scripts/signal/movfun.m
@anchor{XREFmovfun}
@deftypefn  {} {@var{y} =} movfun (@var{fcn}, @var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movfun (@var{fcn}, @var{x}, @var{[@var{nb}, @var{na}}])
@deftypefnx {} {@var{y} =} movfun (@dots{}, "@var{property}", @var{value})

Apply function @var{fcn} to a moving window of length @var{wlen} on data
@var{x}.

If @var{wlen} is a scalar, the function @var{fcn} is applied to a moving
window of length @var{wlen}.  When @var{wlen} is an odd number the window is
symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on either
side of the central element.  For example, when calculating the output at
index 5 with a window length of 3, @code{movfun} uses data elements
@w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window is
asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movfun} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

During calculations the data input @var{x} is reshaped into a 2-dimensional
@var{wlen}-by-@var{N} matrix and @var{fcn} is called on this new matrix.
Therefore, @var{fcn} must accept an array input argument and apply the
computation along dimension 1, i.e., down the columns of the array.

When applied to an array (possibly multi-dimensional) with @var{n} columns,
@var{fcn} may return a result in either of two formats: @w{Format 1)}
an array of size 1-by-@var{n}-by-@var{dim3}-by-@dots{}-by-@var{dimN}.  This
is the typical output format from Octave core functions.  Type
@code{demo ("movfun", 5)} for an example of this use case.
@w{Format 2)} a row vector of length
@code{@var{n} * @var{numel_higher_dims}} where @var{numel_higher_dims} is
@w{@code{prod (size (@var{x})(3:end))}}.  The output of @var{fcn} for the
i-th input column must be found in the output at indices
@w{@code{i:@var{n}:(@var{n}*@var{numel_higher_dims})}}.
This format is useful when concatenating functions into arrays, or when
using @code{nthargout}.  Type @code{demo ("movfun", 6)} for an example of
this case.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"dim"}
Operate along the dimension specified, rather than the default of the first
non-singleton dimension.

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = @var{fcn} (@var{x}(1:2))}, and
@code{@var{y}(end) = @var{fcn} (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = @var{fcn} ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = @var{fcn} ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @var{fcn} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = @var{fcn} ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = @var{fcn} ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = @var{fcn} ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = @var{fcn} ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = @var{fcn} ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = @var{fcn} ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

Note that for some of these choices, the window size at the boundaries is
not the same as for the central part, and @var{fcn} must work in these
cases.

@item @qcode{"nancond"}
Controls whether @code{NaN} and @code{NA} values should be included (value:
@qcode{"includenan"}), or excluded (value: @qcode{"omitnan"}), from the data
passed to @var{fcn}.  The default is @qcode{"includenan"}.  Caution:
The @qcode{"omitnan"} option is not yet implemented.

@item @qcode{"outdim"}
A row vector that selects which dimensions of the calculation will appear
in the output @var{y}.  This is only useful when @var{fcn} returns an
N-dimensional array in @w{Format 1}.  The default is to return all output
dimensions.

@end table

Programming Note: The property @qcode{"outdim"} can be used to save memory
when the output of @var{fcn} has many dimensions, or when a wrapper to the
base function that selects the desired outputs is too costly.  When memory
is not an issue, the easiest way to select output dimensions is to first
calculate the complete result with @code{movfun} and then filter that result
with indexing.  If code complexity is not an issue then a wrapper can be
created using anonymous functions.  For example, if @code{basefcn}
is a function returning a @var{K}-dimensional row output, and only
dimension @var{D} is desired, then the following wrapper could be used.

@example
@group
@var{fcn} = @@(x) basefcn (x)(:,columns(x) * (@var{D}-1) + (1:columns(x)));
@var{y} = movfun (@@fcn, @dots{});
@end group
@end example

@xseealso{@ref{XREFmovslice,,movslice}, @ref{XREFprepad,,prepad}, @ref{XREFpostpad,,postpad}, @ref{XREFpermute,,permute}, @ref{XREFreshape,,reshape}}
@end deftypefn


@c movslice scripts/signal/movslice.m
@anchor{XREFmovslice}
@deftypefn  {} {@var{slcidx} =} movslice (@var{N}, @var{wlen})
@deftypefnx {} {[@var{slcidx}, @var{C}, @var{Cpre}, @var{Cpost}, @var{win}] =} movslice (@dots{})
Generate indices to slice a vector of length @var{N} into windows
of length @var{wlen}.

The input @var{N} must be a positive integer.

The moving window length input @var{wlen} can either be a scalar not equal
to 1 or a 2-element array of integers.  For scalar values, if odd the window
is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on either
side of the central element.  If @var{wlen} is even the window is asymmetric
and has @w{@code{@var{wlen}/2}} elements to the left of the central element
and @w{@code{@var{wlen}/2 - 1}} elements to the right of the central
element.  When @var{wlen} is a 2-element array,
@w{@code{[@var{nb}, @var{na}]}}, the window includes @var{nb} elements to
the left of the current element and @var{na} elements to the right of the
current element.

The output @var{slcidx} is an array of indices of the slices that fit fully
within the vector, where each column is an individual slice as the window
moves from left to right.  The slices have @var{wlen} elements for scalar
@var{wlen}, or @w{@code{@var{nb} + @var{na} + 1}} elements for array valued
@var{wlen}.

Optional output @var{C} is an row vector of window center positions where
the window stays fully within the vector.

Optional outputs @var{Cpre} and @var{Cpost} contain the vector elements at
the start and end of the vector, respectively, that result in the window
extending beyond the ends of the vector.

Optional output @var{win} is a column vector with the same number of rows
as @var{slcidx} that contains the moving window defined as a center
relative position stencil.

@xseealso{@ref{XREFmovfun,,movfun}}
@end deftypefn


@c movmad scripts/statistics/movmad.m
@anchor{XREFmovmad}
@deftypefn  {} {@var{y} =} movmad (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movmad (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movmad (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movmad (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movmad (@dots{}, @var{property}, @var{value})
Calculate the moving mean absolute deviation over a sliding window of length
@var{wlen} on data @var{x}.

If @var{wlen} is a scalar, the function @code{mad} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movmad} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movmad} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{mad}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = mad (@var{x}(1:2))}, and
@code{@var{y}(end) = mad (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = mad ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = mad ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{mad} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = mad ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = mad ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = mad ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = mad ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = mad ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = mad ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movmax scripts/statistics/movmax.m
@anchor{XREFmovmax}
@deftypefn  {} {@var{y} =} movmax (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movmax (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movmax (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movmax (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movmax (@dots{}, @var{property}, @var{value})
Calculate the moving maximum over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{max} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movmax} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movmax} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{max}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = max (@var{x}(1:2))}, and
@code{@var{y}(end) = max (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = max ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = max ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{max} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = max ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = max ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = max ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = max ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = max ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = max ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movmean scripts/statistics/movmean.m
@anchor{XREFmovmean}
@deftypefn  {} {@var{y} =} movmean (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movmean (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movmean (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movmean (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movmean (@dots{}, @var{property}, @var{value})
Calculate the moving average over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{mean} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movmean} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movmean} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{mean}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = mean (@var{x}(1:2))}, and
@code{@var{y}(end) = mean (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = mean ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = mean ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{mean} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = mean ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = mean ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = mean ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = mean ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = mean ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = mean ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movmedian scripts/statistics/movmedian.m
@anchor{XREFmovmedian}
@deftypefn  {} {@var{y} =} movmedian (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movmedian (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movmedian (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movmedian (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movmedian (@dots{}, @var{property}, @var{value})
Calculate the moving median over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{movmedian} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movmedian} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movmedian} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to
@code{movmedian}.  The default is @qcode{"includenan"}.  Caution: the
@qcode{"omitnan"} option is not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = movmedian (@var{x}(1:2))}, and
@code{@var{y}(end) = movmedian (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = movmedian ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = movmedian ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{movmedian} handles
@code{NaN}, and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = movmedian ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = movmedian ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = movmedian ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = movmedian ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = movmedian ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = movmedian ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movmin scripts/statistics/movmin.m
@anchor{XREFmovmin}
@deftypefn  {} {@var{y} =} movmin (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movmin (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movmin (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movmin (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movmin (@dots{}, @var{property}, @var{value})
Calculate the moving minimum over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{min} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movmin} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movmin} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{min}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = min (@var{x}(1:2))}, and
@code{@var{y}(end) = min (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = min ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = min ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{min} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = min ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = min ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = min ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = min ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = min ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = min ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movprod scripts/statistics/movprod.m
@anchor{XREFmovprod}
@deftypefn  {} {@var{y} =} movprod (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movprod (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movprod (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movprod (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movprod (@dots{}, @var{property}, @var{value})
Calculate the moving product over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{movprod} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movprod} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movprod} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{movprod}.
The default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"}
option is not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = movprod (@var{x}(1:2))}, and
@code{@var{y}(end) = movprod (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = movprod ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = movprod ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{movprod} handles
@code{NaN}, and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = movprod ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = movprod ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = movprod ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = movprod ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = movprod ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = movprod ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movstd scripts/statistics/movstd.m
@anchor{XREFmovstd}
@deftypefn  {} {@var{y} =} movstd (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movstd (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movstd (@dots{}, @var{opt})
@deftypefnx {} {@var{y} =} movstd (@dots{}, @var{opt}, @var{dim})
@deftypefnx {} {@var{y} =} movstd (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movstd (@dots{}, @var{property}, @var{value})
Calculate the moving standard deviation over a sliding window of length
@var{wlen} on data @var{x}.

If @var{wlen} is a scalar, the function @code{movstd} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movstd} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movstd} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

The optional argument @var{opt} determines the type of normalization to use.
Valid values are

@table @asis
@item 0:
  normalize with @math{N-1}, provides the square root of the best unbiased
estimator of the variance [default]

@item 1:
  normalize with @math{N}, this provides the square root of the second
moment around the mean
@end table

If the optional argument @var{dim} is given, operate along this dimension.
The normalization argument @var{opt} must be given before the dimension.

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{movstd}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = movstd (@var{x}(1:2))}, and
@code{@var{y}(end) = movstd (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = movstd ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = movstd ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{movstd} handles
@code{NaN}, and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = movstd ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = movstd ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = movstd ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = movstd ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = movstd ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = movstd ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovsum,,movsum}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movsum scripts/statistics/movsum.m
@anchor{XREFmovsum}
@deftypefn  {} {@var{y} =} movsum (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movsum (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movsum (@dots{}, @var{dim})
@deftypefnx {} {@var{y} =} movsum (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movsum (@dots{}, @var{property}, @var{value})
Calculate the moving sum over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{movsum} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movsum} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movsum} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

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

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{movsum}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = movsum (@var{x}(1:2))}, and
@code{@var{y}(end) = movsum (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = movsum ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = movsum ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{movsum} handles
@code{NaN}, and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = movsum ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = movsum ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = movsum ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = movsum ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = movsum ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = movsum ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovvar,,movvar}}
@end deftypefn


@c movvar scripts/statistics/movvar.m
@anchor{XREFmovvar}
@deftypefn  {} {@var{y} =} movvar (@var{x}, @var{wlen})
@deftypefnx {} {@var{y} =} movvar (@var{x}, [@var{nb}, @var{na}])
@deftypefnx {} {@var{y} =} movvar (@dots{}, @var{opt})
@deftypefnx {} {@var{y} =} movvar (@dots{}, @var{opt}, @var{dim})
@deftypefnx {} {@var{y} =} movvar (@dots{}, "@var{nancond}")
@deftypefnx {} {@var{y} =} movvar (@dots{}, @var{property}, @var{value})
Calculate the moving variance over a sliding window of length @var{wlen} on
data @var{x}.

If @var{wlen} is a scalar, the function @code{var} is applied to a
moving window of length @var{wlen}.  When @var{wlen} is an odd number the
window is symmetric and includes @w{@code{(@var{wlen} - 1) / 2}} elements on
either side of the central element.  For example, when calculating the
output at index 5 with a window length of 3, @code{movvar} uses data
elements @w{@code{[4, 5, 6]}}.  If @var{wlen} is an even number, the window
is asymmetric and has @w{@code{@var{wlen}/2}} elements to the left of the
central element and @w{@code{@var{wlen}/2 - 1}} elements to the right of the
central element.  For example, when calculating the output at index 5 with a
window length of 4, @code{movvar} uses data elements
@w{@code{[3, 4, 5, 6]}}.

If @var{wlen} is an array with two elements @w{@code{[@var{nb}, @var{na}]}},
the function is applied to a moving window @code{-@var{nb}:@var{na}}.  This
window includes @var{nb} number of elements @emph{before} the current
element and @var{na} number of elements @emph{after} the current element.
The current element is always included.  For example, given
@w{@code{@var{wlen} = [3, 0]}}, the data used to calculate index 5 is
@w{@code{[2, 3, 4, 5]}}.

The optional argument @var{opt} determines the type of normalization to use.
Valid values are

@table @asis
@item 0:
  normalize with @math{N-1}, provides the best unbiased estimator of the
variance [default]

@item 1:
  normalizes with @math{N}, this provides the second moment around the mean
@end table

If the optional argument @var{dim} is given, operate along this dimension.
The normalization argument @var{opt} must be given before the dimension.

The optional string argument @qcode{"@var{nancond}"} controls whether
@code{NaN} and @code{NA} values should be included (@qcode{"includenan"}),
or excluded (@qcode{"omitnan"}), from the data passed to @code{var}.  The
default is @qcode{"includenan"}.  Caution: the @qcode{"omitnan"} option is
not yet implemented.

The calculation can be controlled by specifying @var{property}/@var{value}
pairs.  Valid properties are

@table @asis

@item @qcode{"Endpoints"}

This property controls how results are calculated at the boundaries
(@w{endpoints}) of the window.  Possible values are:

@table @asis
@item @qcode{"shrink"}  (default)
The window is truncated at the beginning and end of the array to exclude
elements for which there is no source data.  For example, with a window of
length 3, @code{@var{y}(1) = var (@var{x}(1:2))}, and
@code{@var{y}(end) = var (@var{x}(end-1:end))}.

@item @qcode{"discard"}
Any @var{y} values that use a window extending beyond the original
data array are deleted.  For example, with a 10-element data vector and a
window of length 3, the output will contain only 8 elements.  The first
element would require calculating the function over indices
@w{@code{[0, 1, 2]}} and is therefore discarded.  The last element would
require calculating the function over indices @w{@code{[9, 10, 11]}} and is
therefore discarded.

@item @qcode{"fill"}
Any window elements outside the data array are replaced by @code{NaN}.  For
example, with a window of length 3,
@code{@var{y}(1) = var ([NaN, @var{x}(1:2)])}, and
@code{@var{y}(end) = var ([@var{x}(end-1:end), NaN])}.
This option usually results in @var{y} having @code{NaN} values at the
boundaries, although it is influenced by how @code{var} handles @code{NaN},
and also by the property @qcode{"nancond"}.

@item @var{user_value}
Any window elements outside the data array are replaced by the specified
value @var{user_value} which must be a numeric scalar.  For example, with a
window of length 3,
@code{@var{y}(1) = var ([@var{user_value}, @var{x}(1:2)])}, and
@code{@var{y}(end) = var ([@var{x}(end-1:end), @var{user_value}])}.
A common choice for @var{user_value} is 0.

@item @qcode{"same"}
Any window elements outside the data array are replaced by the value of
@var{x} at the boundary.  For example, with a window of length 3,
@code{@var{y}(1) = var ([@var{x}(1), @var{x}(1:2)])}, and
@code{@var{y}(end) = var ([@var{x}(end-1:end), @var{x}(end)])}.

@item @qcode{"periodic"}
The window is wrapped so that any missing data elements are taken from
the other side of the data.  For example, with a window of length 3,
@code{@var{y}(1) = var ([@var{x}(end), @var{x}(1:2)])}, and
@code{@var{y}(end) = var ([@var{x}(end-1:end), @var{x}(1)])}.

@end table

@item @qcode{"SamplePoints"}
Caution: This option is not yet implemented.

@end table

Programming Note: This function is a wrapper which calls @code{movfun}.
For additional options and documentation, @pxref{XREFmovfun,,@code{movfun}}.

@xseealso{@ref{XREFmovfun,,movfun}, @ref{XREFmovslice,,movslice}, @ref{XREFmovmad,,movmad}, @ref{XREFmovmax,,movmax}, @ref{XREFmovmean,,movmean}, @ref{XREFmovmedian,,movmedian}, @ref{XREFmovmin,,movmin}, @ref{XREFmovprod,,movprod}, @ref{XREFmovstd,,movstd}, @ref{XREFmovsum,,movsum}}
@end deftypefn


@node Basic Statistical Functions
@section Basic Statistical Functions

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

@c center scripts/statistics/center.m
@anchor{XREFcenter}
@deftypefn  {} {@var{y} =} center (@var{x})
@deftypefnx {} {@var{y} =} center (@var{x}, @var{dim})
Center data by subtracting its mean.

If @var{x} is a vector, subtract its mean.

If @var{x} is a matrix, do the above for each column.

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

Programming Note: @code{center} has obvious application for normalizing
statistical data.  It is also useful for improving the precision of general
numerical calculations.  Whenever there is a large value that is common
to a batch of data, the mean can be subtracted off, the calculation
performed, and then the mean added back to obtain the final answer.
@xseealso{@ref{XREFzscore,,zscore}}
@end deftypefn


@c zscore scripts/statistics/zscore.m
@anchor{XREFzscore}
@deftypefn  {} {@var{z} =} zscore (@var{x})
@deftypefnx {} {@var{z} =} zscore (@var{x}, @var{opt})
@deftypefnx {} {@var{z} =} zscore (@var{x}, @var{opt}, @var{dim})
@deftypefnx {} {[@var{z}, @var{mu}, @var{sigma}] =} zscore (@dots{})
Compute the Z score of @var{x}.

If @var{x} is a vector, subtract its mean and divide by its standard
deviation.  If the standard deviation is zero, divide by 1 instead.

The optional parameter @var{opt} determines the normalization to use when
computing the standard deviation and has the same definition as the
corresponding parameter for @code{std}.

If @var{x} is a matrix, calculate along the first non-singleton dimension.
If the third optional argument @var{dim} is given, operate along this
dimension.

The optional outputs @var{mu} and @var{sigma} contain the mean and standard
deviation.

@xseealso{@ref{XREFmean,,mean}, @ref{XREFstd,,std}, @ref{XREFcenter,,center}}
@end deftypefn


@c normalize scripts/statistics/normalize.m
@anchor{XREFnormalize}
@deftypefn  {} {@var{z} =} normalize (@var{x})
@deftypefnx {} {@var{z} =} normalize (@var{x}, @var{dim})
@deftypefnx {} {@var{z} =} normalize (@dots{}, @var{method})
@deftypefnx {} {@var{z} =} normalize (@dots{}, @var{method}, @var{option})
@deftypefnx {} {@var{z} =} normalize (@dots{}, @var{scale}, @var{scaleoption}, @var{center}, @var{centeroption})
@deftypefnx {} {[@var{z}, @var{c}, @var{s}] =} normalize (@dots{})

Return a normalization of the data in @var{x} using one of several available
scaling and centering methods.

@code{normalize} by default will return the @code{zscore} of @var{x},
defined as the number of standard deviations each element is from the mean
of @var{x}.  This is equivalent to centering at the mean of the data and
scaling by the standard deviation.

The returned value @var{z} will have the same size as @var{x}.  The optional
return variables @var{c} and @var{s} are the centering and scaling factors
used in the normalization such that:

@example
@group
  @tcode{@var{z} = (@var{x} - @var{c}) ./ @var{s}}
@end group
@end example

If @var{x} is a vector, @code{normalize} will operate on the data in
@var{x}.

If @var{x} is a matrix, @code{normalize} will operate independently on
each column in @var{x}.

If @var{x} is an N-dimensional array, @code{normalize} will operate
independently on the first non-singleton dimension in @var{x}.

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

The optional inputs @var{method} and @var{option} can be used to specify the
type of normalization performed on @var{x}.  Note that only the
@option{scale} and @option{center} options may be specified together using
any of the methods defined below.  Valid normalization methods are:

@table @code
@item zscore
(Default) Normalizes the elements in @var{x} to the scaled distance from a
 central value.  Valid Options:

@table @code
@item std
   (Default) Data is centered at @code{mean (@var{x})} and scaled by the
     standard deviation.

@item robust
   Data is centered at @code{median (@var{x})} and scaled by the median
   absolute deviation.
@end table

@item norm
@var{z} is the general vector norm of @var{x}, with @var{option} being the
normalization factor @var{p} that determines the vector norm type according
to:
@tex
$$Z = \left (\sum_k \left | X_k \right |^P  \right )^{1/P}$$
@end tex
@ifnottex

@example
@group
  @tcode{@var{z} = [sum (abs (@var{x}) .^ @var{p})] ^ (1/@var{p})}
@end group
@end example

@end ifnottex
@var{p} can be any positive scalar, specific values being:

@table @code
@item @var{p} = 1
@var{x} is normalized by @code{sum (abs (@var{x}))}.

@item @var{p} = 2
   (Default) @var{x} is normalized by the Euclidian norm, or vector
   magnitude, of the elements.

@item @var{P} = Inf
@var{x} is normalized by @code{max (abs (@var{x}))}.
@end table

@item scale
@var{x} is scaled by a factor determined by @var{option}, which can be a
numeric scalar or one of the following:

@table @code
@item std
   (Default) @var{x} is scaled by its standard deviation.

@item mad
@var{x} is scaled by its median absolute deviation.

@item first
@var{x} is scaled by its first element.

@item iqr
@var{x} is scaled by its interquartile range.
@end table

@item range
@var{x} is scaled to fit the range specified by @var{option} as a two
element scalar row vector.  The default range is [0, 1].

@item center
@var{x} is shifted by an amount determined by @var{option}, which can be a
numeric scalar or one of the following:

@table @code
@item mean
   (Default) @var{x} is shifted by @code{mean (@var{x})}.

@item median
@var{x} is shifted by @code{median (@var{x})}.
@end table

@item medianiqr
@var{x} is shifted by @code{median (@var{x})} and scaled by the
interquartile range.
@end table

Known @sc{matlab} incompatibilities:

@enumerate
@item
The option @option{DataVariables} is not yet implemented for Table class
@var{x} inputs.

@item
Certain arrays containing NaN elements may not return @sc{matlab} compatible
output.
@end enumerate

@xseealso{@ref{XREFzscore,,zscore}, @ref{XREFiqr,,iqr}, @ref{XREFnorm,,norm}, @ref{XREFrescale,,rescale}, @ref{XREFstd,,std}, @ref{XREFmedian,,median}, @ref{XREFmean,,mean}, @ref{XREFmad,,mad}}
@end deftypefn


@c histc scripts/statistics/histc.m
@anchor{XREFhistc}
@deftypefn  {} {@var{n} =} histc (@var{x}, @var{edges})
@deftypefnx {} {@var{n} =} histc (@var{x}, @var{edges}, @var{dim})
@deftypefnx {} {[@var{n}, @var{idx}] =} histc (@dots{})
Compute histogram counts.

When @var{x} is a vector, the function counts the number of elements of
@var{x} that fall in the histogram bins defined by @var{edges}.  This
must be a vector of monotonically increasing values that define the edges
of the histogram bins.
@tex
$n(k)$
@end tex
@ifnottex
@code{@var{n}(k)}
@end ifnottex
contains the number of elements in @var{x} for which
@tex
$@var{edges}(k) <= @var{x} < @var{edges}(k+1)$.
@end tex
@ifnottex
@code{@var{edges}(k) <= @var{x} < @var{edges}(k+1)}.
@end ifnottex
The final element of @var{n} contains the number of elements of @var{x}
exactly equal to the last element of @var{edges}.

When @var{x} is an @math{N}-dimensional array, the computation is carried
out along dimension @var{dim}.  If not specified @var{dim} defaults to the
first non-singleton dimension.

When a second output argument is requested an index matrix is also returned.
The @var{idx} matrix has the same size as @var{x}.  Each element of
@var{idx} contains the index of the histogram bin in which the
corresponding element of @var{x} was counted.
@xseealso{@ref{XREFhist,,hist}}
@end deftypefn


@noindent
@code{unique} function documented at @ref{XREFunique,,unique} is often
useful for statistics.

@c nchoosek scripts/specfun/nchoosek.m
@anchor{XREFnchoosek}
@deftypefn  {} {@var{c} =} nchoosek (@var{n}, @var{k})
@deftypefnx {} {@var{c} =} nchoosek (@var{set}, @var{k})

Compute the binomial coefficient of @var{n} or list all possible
combinations of a @var{set} of items.

If @var{n} is a scalar then calculate the binomial coefficient
of @var{n} and @var{k} which is defined as
@tex
$$
 {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!}
               = {n! \over k! (n-k)!}
$$
@end tex
@ifnottex

@example
@group
 /   \
 | n |    n (n-1) (n-2) @dots{} (n-k+1)       n!
 |   |  = ------------------------- =  ---------
 | k |               k!                k! (n-k)!
 \   /
@end group
@end example

@end ifnottex
@noindent
This is the number of combinations of @var{n} items taken in groups of
size @var{k}.

If the first argument is a vector, @var{set}, then generate all
combinations of the elements of @var{set}, taken @var{k} at a time, with
one row per combination.  The result @var{c} has @var{k} columns and
@w{@code{nchoosek (length (@var{set}), @var{k})}} rows.

For example:

How many ways can three items be grouped into pairs?

@example
@group
nchoosek (3, 2)
   @result{} 3
@end group
@end example

What are the possible pairs?

@example
@group
nchoosek (1:3, 2)
   @result{}  1   2
       1   3
       2   3
@end group
@end example

Programming Note: When calculating the binomial coefficient @code{nchoosek}
works only for non-negative, integer arguments.  Use @code{bincoeff} for
non-integer and negative scalar arguments, or for computing many binomial
coefficients at once with vector inputs for @var{n} or @var{k}.

@xseealso{@ref{XREFbincoeff,,bincoeff}, @ref{XREFperms,,perms}}
@end deftypefn


@c perms scripts/specfun/perms.m
@anchor{XREFperms}
@deftypefn  {} {@var{P} =} perms (@var{v})
@deftypefnx {} {@var{P} =} perms (@var{v}, "unique")
Generate all permutations of vector @var{v} with one row per permutation.

Results are returned in inverse lexicographic order.  The result has size
@code{factorial (@var{n}) * @var{n}}, where @var{n} is the length of
@var{v}.  Any repeated elements are included in the output.

If the optional argument @qcode{"unique"} is given then only unique
permutations are returned, using less memory and generally taking less time
than calling @code{unique (perms (@var{v}), "rows")}.

Example 1

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

Example 2

@example
@group
perms ([1, 1, 2, 2], "unique")
@result{}
  1   1   2   2
  1   2   1   2
  1   2   2   1
  2   1   1   2
  2   1   2   1
  2   2   1   1
@end group
@end example

Programming Note: If the @qcode{"unique"} option is not used, the length of
@var{v} should be no more than 10-12 to limit memory consumption.  Even with
@qcode{"unique"}, there should be no more than 10-12 unique elements in
@var{v}.
@xseealso{@ref{XREFpermute,,permute}, @ref{XREFrandperm,,randperm}, @ref{XREFnchoosek,,nchoosek}}
@end deftypefn


@c ranks scripts/statistics/ranks.m
@anchor{XREFranks}
@deftypefn  {} {@var{y} =} ranks (@var{x})
@deftypefnx {} {@var{y} =} ranks (@var{x}, @var{dim})
@deftypefnx {} {@var{y} =} ranks (@var{x}, @var{dim}, @var{rtype})
Return the ranks (in the sense of order statistics) of @var{x} along the
first non-singleton dimension adjusted for ties.

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

The optional parameter @var{rtype} determines how ties are handled.  All
examples below assume an input of @code{[ 1, 2, 2, 4 ]}.

@table @asis
@item 0 or @qcode{"fractional"} (default) for fractional ranking (1, 2.5,
2.5, 4);

@item 1 or @qcode{"competition"} for competition ranking (1, 2, 2, 4);

@item 2 or @qcode{"modified"} for modified competition ranking (1, 3, 3, 4);

@item 3 or @qcode{"ordinal"} for ordinal ranking (1, 2, 3, 4);

@item 4 or @qcode{"dense"} for dense ranking (1, 2, 2, 3).
@end table

@xseealso{@ref{XREFspearman,,spearman}, @ref{XREFkendall,,kendall}}
@end deftypefn


@c run_count scripts/statistics/run_count.m
@anchor{XREFrun_count}
@deftypefn  {} {@var{cnt} =} run_count (@var{x}, @var{n})
@deftypefnx {} {@var{cnt} =} run_count (@var{x}, @var{n}, @var{dim})
Count the upward runs along the first non-singleton dimension of @var{x}
of length 1, 2, @dots{}, @var{n}-1 and greater than or equal to @var{n}.

If the optional argument @var{dim} is given then operate along this
dimension.
@xseealso{@ref{XREFrunlength,,runlength}}
@end deftypefn


@c runlength scripts/statistics/runlength.m
@anchor{XREFrunlength}
@deftypefn  {} {count =} runlength (@var{x})
@deftypefnx {} {[count, value] =} runlength (@var{x})
Find the lengths of all sequences of common values.

@var{count} is a vector with the lengths of each repeated value.

The optional output @var{value} contains the value that was repeated in
the sequence.

@example
@group
runlength ([2, 2, 0, 4, 4, 4, 0, 1, 1, 1, 1])
@result{}   2   1   3   1   4
@end group
@end example
@xseealso{@ref{XREFrun_count,,run_count}}
@end deftypefn


@node Correlation and Regression Analysis
@section Correlation and Regression Analysis

@c FIXME: Need Intro Here

@c cov scripts/statistics/cov.m
@anchor{XREFcov}
@deftypefn  {} {@var{c} =} cov (@var{x})
@deftypefnx {} {@var{c} =} cov (@var{x}, @var{opt})
@deftypefnx {} {@var{c} =} cov (@var{x}, @var{y})
@deftypefnx {} {@var{c} =} cov (@var{x}, @var{y}, @var{opt})
Compute the covariance matrix.

If each row of @var{x} and @var{y} is an observation, and each column is
a variable, then the @w{(@var{i}, @var{j})-th} entry of
@code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th
variable in @var{x} and the @var{j}-th variable in @var{y}.
@tex
$$
\sigma_{ij} = {1 \over N-1} \sum_{i=1}^N (x_i - \bar{x})(y_i - \bar{y})
$$
where $\bar{x}$ and $\bar{y}$ are the mean values of @var{x} and @var{y}.
@end tex
@ifnottex

@example
cov (@var{x}) = 1/(N-1) * SUM_i (@var{x}(i) - mean(@var{x})) * (@var{y}(i) - mean(@var{y}))
@end example

@noindent
where @math{N} is the length of the @var{x} and @var{y} vectors.

@end ifnottex

If called with one argument, compute @code{cov (@var{x}, @var{x})}, the
covariance between the columns of @var{x}.

The argument @var{opt} determines the type of normalization to use.
Valid values are

@table @asis
@item 0:
  normalize with @math{N-1}, provides the best unbiased estimator of the
covariance [default]

@item 1:
  normalize with @math{N}, this provides the second moment around the mean
@end table

Compatibility Note:: Octave always treats rows of @var{x} and @var{y}
as multivariate random variables.
For two inputs, however, @sc{matlab} treats @var{x} and @var{y} as two
univariate distributions regardless of their shapes, and will calculate
@code{cov ([@var{x}(:), @var{y}(:)])} whenever the number of elements in
@var{x} and @var{y} are equal.  This will result in a 2x2 matrix.
Code relying on @sc{matlab}'s definition will need to be changed when
running in Octave.
@xseealso{@ref{XREFcorr,,corr}}
@end deftypefn


@c corr scripts/statistics/corr.m
@anchor{XREFcorr}
@deftypefn  {} {@var{r} =} corr (@var{x})
@deftypefnx {} {@var{r} =} corr (@var{x}, @var{y})
Compute matrix of correlation coefficients.

If each row of @var{x} and @var{y} is an observation and each column is
a variable, then the @w{(@var{i}, @var{j})-th} entry of
@code{corr (@var{x}, @var{y})} is the correlation between the
@var{i}-th variable in @var{x} and the @var{j}-th variable in @var{y}.
@tex
$$
{\rm corr}(x,y) = {{\rm cov}(x,y) \over {\rm std}(x) \, {\rm std}(y)}
$$
@end tex
@ifnottex

@example
corr (@var{x},@var{y}) = cov (@var{x},@var{y}) / (std (@var{x}) * std (@var{y}))
@end example

@end ifnottex
If called with one argument, compute @code{corr (@var{x}, @var{x})},
the correlation between the columns of @var{x}.
@xseealso{@ref{XREFcov,,cov}}
@end deftypefn


@c corrcoef scripts/statistics/corrcoef.m
@anchor{XREFcorrcoef}
@deftypefn  {} {@var{r} =} corrcoef (@var{x})
@deftypefnx {} {@var{r} =} corrcoef (@var{x}, @var{y})
@deftypefnx {} {@var{r} =} corrcoef (@dots{}, @var{param}, @var{value}, @dots{})
@deftypefnx {} {[@var{r}, @var{p}] =} corrcoef (@dots{})
@deftypefnx {} {[@var{r}, @var{p}, @var{lci}, @var{hci}] =} corrcoef (@dots{})
Compute a matrix of correlation coefficients.

@var{x} is an array where each column contains a variable and each row is
an observation.

If a second input @var{y} (of the same size as @var{x}) is given then
calculate the correlation coefficients between @var{x} and @var{y}.

@var{param}, @var{value} are optional pairs of parameters and values which
modify the calculation.  Valid options are:

@table @asis
@item @qcode{"alpha"}
Confidence level used for the bounds of the confidence interval, @var{lci}
and @var{hci}.  Default is 0.05, i.e., 95% confidence interval.

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

Output @var{r} is a matrix of Pearson's product moment correlation
coefficients for each pair of variables.

Output @var{p} is a matrix of pair-wise p-values testing for the null
hypothesis of a correlation coefficient of zero.

Outputs @var{lci} and @var{hci} are matrices containing, respectively, the
lower and higher bounds of the 95% confidence interval of each correlation
coefficient.
@xseealso{@ref{XREFcorr,,corr}, @ref{XREFcov,,cov}}
@end deftypefn


@c spearman scripts/statistics/spearman.m
@anchor{XREFspearman}
@deftypefn  {} {@var{rho} =} spearman (@var{x})
@deftypefnx {} {@var{rho} =} spearman (@var{x}, @var{y})
@cindex Spearman's Rho
Compute Spearman's rank correlation coefficient
@tex
$\rho$.
@end tex
@ifnottex
@var{rho}.
@end ifnottex

For two data vectors @var{x} and @var{y}, Spearman's
@tex
$\rho$
@end tex
@ifnottex
@var{rho}
@end ifnottex
is the correlation coefficient of the ranks of @var{x} and @var{y}.

If @var{x} and @var{y} are drawn from independent distributions,
@tex
$\rho$
@end tex
@ifnottex
@var{rho}
@end ifnottex
has zero mean and variance
@tex
$1 / (N - 1)$,
@end tex
@ifnottex
@code{1 / (N - 1)},
@end ifnottex
where @math{N} is the length of the @var{x} and @var{y} vectors, and is
asymptotically normally distributed.

@code{spearman (@var{x})} is equivalent to
@code{spearman (@var{x}, @var{x})}.
@xseealso{@ref{XREFranks,,ranks}, @ref{XREFkendall,,kendall}}
@end deftypefn


@c kendall scripts/statistics/kendall.m
@anchor{XREFkendall}
@deftypefn  {} {@var{tau} =} kendall (@var{x})
@deftypefnx {} {@var{tau} =} kendall (@var{x}, @var{y})
@cindex Kendall's Tau
Compute Kendall's
@tex
$\tau$.
@end tex
@ifnottex
@var{tau}.
@end ifnottex

For two data vectors @var{x}, @var{y} of common length @math{N}, Kendall's
@tex
$\tau$
@end tex
@ifnottex
@var{tau}
@end ifnottex
is the correlation of the signs of all rank differences of
@var{x} and @var{y}; i.e., if both @var{x} and @var{y} have distinct
entries, then

@tex
$$ \tau = {1 \over N(N-1)} \sum_{i,j} {\rm sign}(q_i-q_j) \, {\rm sign}(r_i-r_j) $$
@end tex
@ifnottex

@example
@group
         1
@var{tau} = -------   SUM sign (@var{q}(i) - @var{q}(j)) * sign (@var{r}(i) - @var{r}(j))
      N (N-1)   i,j
@end group
@end example

@end ifnottex
@noindent
in which the
@tex
$q_i$ and $r_i$
@end tex
@ifnottex
@var{q}(i) and @var{r}(i)
@end ifnottex
are the ranks of @var{x} and @var{y}, respectively.

If @var{x} and @var{y} are drawn from independent distributions,
Kendall's
@tex
$\tau$
@end tex
@ifnottex
@var{tau}
@end ifnottex
is asymptotically normal with mean 0 and variance
@tex
${2 (2N+5) \over 9N(N-1)}$.
@end tex
@ifnottex
@code{(2 * (2N+5)) / (9 * N * (N-1))}.
@end ifnottex

@code{kendall (@var{x})} is equivalent to @code{kendall (@var{x},
@var{x})}.
@xseealso{@ref{XREFranks,,ranks}, @ref{XREFspearman,,spearman}}
@end deftypefn


@node Distributions
@section Distributions

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

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

@tex
\vskip 6pt
{\hbox to \hsize {\hfill\vbox{\offinterlineskip \tabskip=0pt
\halign{
\vrule height2.0ex depth1.ex width 0.6pt #\tabskip=0.3em &
# \hfil & \vrule # & # \hfil & \vrule # & # \hfil & \vrule # & # \hfil &
# \vrule width 0.6pt \tabskip=0pt\cr
\noalign{\hrule height 0.6pt}
& {\bf Distribution} && {\bf PDF}      && {\bf CDF}     && {\bf Quantile}&\cr
\noalign{\hrule}
&Univariate Discrete       && discrete\_pdf  && discrete\_cdf && discrete\_inv&\cr
&Empirical    && empirical\_pdf  && empirical\_cdf && empirical\_inv&\cr
\noalign{\hrule height 0.6pt}
}}\hfill}}
@end tex
@ifnottex
@multitable @columnfractions .31 .23 .23 .23
@headitem Distribution
  @tab PDF
  @tab CDF
  @tab Quantile
@item Univariate Discrete Distribution
  @tab @code{discrete_pdf}
  @tab @code{discrete_cdf}
  @tab @code{discrete_inv}
@item Empirical Distribution
  @tab @code{empirical_pdf}
  @tab @code{empirical_cdf}
  @tab @code{empirical_inv}
@end multitable
@end ifnottex

@c discrete_pdf scripts/statistics/discrete_pdf.m
@anchor{XREFdiscrete_pdf}
@deftypefn {} {@var{pdf} =} discrete_pdf (@var{x}, @var{v}, @var{p})
For each element of @var{x}, compute the probability density function (PDF)
at @var{x} of a univariate discrete distribution which assumes the values
in @var{v} with probabilities @var{p}.
@end deftypefn


@c discrete_cdf scripts/statistics/discrete_cdf.m
@anchor{XREFdiscrete_cdf}
@deftypefn {} {@var{cdf} =} discrete_cdf (@var{x}, @var{v}, @var{p})
For each element of @var{x}, compute the cumulative distribution function
(CDF) at @var{x} of a univariate discrete distribution which assumes the
values in @var{v} with probabilities @var{p}.
@end deftypefn


@c discrete_inv scripts/statistics/discrete_inv.m
@anchor{XREFdiscrete_inv}
@deftypefn {} {@var{q} =} discrete_inv (@var{x}, @var{v}, @var{p})
For each element of @var{x}, compute the quantile (the inverse of the CDF)
at @var{x} of the univariate distribution which assumes the values in
@var{v} with probabilities @var{p}.
@end deftypefn


@c empirical_pdf scripts/statistics/empirical_pdf.m
@anchor{XREFempirical_pdf}
@deftypefn {} {@var{pdf} =} empirical_pdf (@var{x}, @var{data})
For each element of @var{x}, compute the probability density function (PDF)
at @var{x} of the empirical distribution obtained from the
univariate sample @var{data}.
@end deftypefn


@c empirical_cdf scripts/statistics/empirical_cdf.m
@anchor{XREFempirical_cdf}
@deftypefn {} {@var{cdf} =} empirical_cdf (@var{x}, @var{data})
For each element of @var{x}, compute the cumulative distribution function
(CDF) at @var{x} of the empirical distribution obtained from
the univariate sample @var{data}.
@end deftypefn


@c empirical_inv scripts/statistics/empirical_inv.m
@anchor{XREFempirical_inv}
@deftypefn {} {@var{q} =} empirical_inv (@var{x}, @var{data})
For each element of @var{x}, compute the quantile (the inverse of the CDF)
at @var{x} of the empirical distribution obtained from the
univariate sample @var{data}.
@end deftypefn


@node Random Number Generation
@section 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
@ref{Special Utility Matrices}.

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

@tex
\vskip 6pt
{\hbox to \hsize {\hfill\vbox{\offinterlineskip \tabskip=0pt
\halign{
\vrule height2.0ex depth1.ex width 0.6pt #\tabskip=0.3em &
# \hfil & \vrule # & # \hfil & # \vrule width 0.6pt \tabskip=0pt\cr
\noalign{\hrule height 0.6pt}
& {\bf Distribution}                && {\bf Function} &\cr
\noalign{\hrule}
& Univariate Discrete Distribution  && discrete\_rnd &\cr
& Empirical Distribution            && empirical\_rnd &\cr
& Exponential Distribution          && rande &\cr
& Gamma Distribution                && randg &\cr
& Poisson Distribution              && randp &\cr
& Standard Normal Distribution      && randn &\cr
& Uniform Distribution              && rand &\cr
& Uniform Distribution (integers)   && randi &\cr
\noalign{\hrule height 0.6pt}
}}\hfill}}
@end tex
@ifnottex
@multitable @columnfractions .4 .3
@headitem Distribution                  @tab Function
@item Univariate Discrete Distribution  @tab @code{discrete_rnd}
@item Empirical Distribution            @tab @code{empirical_rnd}
@item Exponential Distribution          @tab @code{rande}
@item Gamma Distribution                @tab @code{randg}
@item Poisson Distribution              @tab @code{randp}
@item Standard Normal Distribution      @tab @code{randn}
@item Uniform Distribution              @tab @code{rand}
@item Uniform Distribution (integers)   @tab @code{randi}
@end multitable
@end ifnottex

@c discrete_rnd scripts/statistics/discrete_rnd.m
@anchor{XREFdiscrete_rnd}
@deftypefn  {} {@var{rnd} =} discrete_rnd (@var{v}, @var{p})
@deftypefnx {} {@var{rnd} =} discrete_rnd (@var{v}, @var{p}, @var{r})
@deftypefnx {} {@var{rnd} =} discrete_rnd (@var{v}, @var{p}, @var{r}, @var{c}, @dots{})
@deftypefnx {} {@var{rnd} =} discrete_rnd (@var{v}, @var{p}, [@var{sz}])
Return a matrix of random samples from the univariate distribution which
assumes the values in @var{v} with probabilities @var{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 @var{sz}.

If no size arguments are given then the result matrix is the common size of
@var{v} and @var{p}.
@end deftypefn


@c empirical_rnd scripts/statistics/empirical_rnd.m
@anchor{XREFempirical_rnd}
@deftypefn  {} {@var{rnd} =} empirical_rnd (@var{data})
@deftypefnx {} {@var{rnd} =} empirical_rnd (@var{data}, @var{r})
@deftypefnx {} {@var{rnd} =} empirical_rnd (@var{data}, @var{r}, @var{c}, @dots{})
@deftypefnx {} {@var{rnd} =} empirical_rnd (@var{data}, [@var{sz}])
Return a matrix of random samples from the empirical distribution obtained
from the univariate sample @var{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 @var{sz}.

If no size arguments are given then the result matrix is a random ordering
of the sample @var{data}.
@end deftypefn

