1 ## Copyright (C) 1996-2012 John W. Eaton
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} skewness (@var{x})
21 ## @deftypefnx {Function File} {} skewness (@var{x}, @var{dim})
22 ## Compute the skewness of the elements of the vector @var{x}.
25 ## {\rm skewness} (x) = {1\over N \sigma^3} \sum_{i=1}^N (x_i-\bar{x})^3
27 ## where $\bar{x}$ is the mean value of $x$.
32 ## skewness (x) = 1/N std(x)^(-3) sum ((x - mean(x)).^3)
38 ## If @var{x} is a matrix, return the skewness along the
39 ## first non-singleton dimension of the matrix. If the optional
40 ## @var{dim} argument is given, operate along this dimension.
41 ## @seealso{var, kurtosis, moment}
44 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
45 ## Created: 29 July 1994
48 function retval = skewness (x, dim)
50 if (nargin != 1 && nargin != 2)
54 if (! (isnumeric (x) || islogical (x)))
55 error ("skewness: X must be a numeric vector or matrix");
61 ## Find the first non-singleton dimension.
62 (dim = find (sz > 1, 1)) || (dim = 1);
64 if (!(isscalar (dim) && dim == fix (dim))
65 || !(1 <= dim && dim <= nd))
66 error ("skewness: DIM must be an integer and a valid dimension");
72 x = center (x, dim); # center also promotes integer to double for next line
73 retval = zeros (sz, class (x));
76 x = sum (x .^ 3, dim);
77 retval(idx) = x(idx) ./ (n * s(idx) .^ 3);
82 %!assert(skewness ([-1,0,1]), 0);
83 %!assert(skewness ([-2,0,1]) < 0);
84 %!assert(skewness ([-1,0,2]) > 0);
85 %!assert(skewness ([-3,0,1]) == -1*skewness([-1,0,3]));
89 %! assert(all (abs (skewness (y) - [0.75, 0.75]) < sqrt (eps)));
91 %!assert (skewness (single(1)), single(0));
93 %% Test input validation
95 %!error skewness (1, 2, 3)
96 %!error skewness (['A'; 'B'])
97 %!error skewness (1, ones(2,2))
98 %!error skewness (1, 1.5)
99 %!error skewness (1, 0)
100 %!error skewness (1, 3)