]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/base/meansq.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / base / meansq.m
1 ## Copyright (C) 1995-2012 Kurt Hornik
2 ## Copyright (C) 2009 Jaroslav Hajek
3 ##
4 ## This file is part of Octave.
5 ##
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
10 ##
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ## General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING.  If not, see
18 ## <http://www.gnu.org/licenses/>.
19
20 ## -*- texinfo -*-
21 ## @deftypefn  {Function File} {} meansq (@var{x})
22 ## @deftypefnx {Function File} {} meansq (@var{x}, @var{dim})
23 ## Compute the mean square of the elements of the vector @var{x}.
24 ## @tex
25 ## $$
26 ## {\rm meansq} (x) = {\sum_{i=1}^N {x_i}^2 \over N}
27 ## $$
28 ## where $\bar{x}$ is the mean value of $x$.
29 ## @end tex
30 ## @ifnottex
31 ##
32 ## @example
33 ## @group
34 ## std (x) = 1/N SUM_i x(i)^2
35 ## @end group
36 ## @end example
37 ##
38 ## @end ifnottex
39 ## For matrix arguments, return a row vector containing the mean square
40 ## of each column.
41 ##
42 ## If the optional argument @var{dim} is given, operate along this dimension.
43 ## @seealso{var, std, moment}
44 ## @end deftypefn
45
46 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
47 ## Description: Compute mean square
48
49 function y = meansq (x, dim)
50
51   if (nargin != 1 && nargin != 2)
52     print_usage ();
53   endif
54
55   if (! (isnumeric (x) || islogical (x)))
56     error ("mean: X must be a numeric vector or matrix");
57   endif
58
59   nd = ndims (x);
60   sz = size (x);
61   if (nargin < 2)
62     ## Find the first non-singleton dimension.
63     (dim = find (sz > 1, 1)) || (dim = 1);
64   else
65     if (!(isscalar (dim) && dim == fix (dim))
66         || !(1 <= dim && dim <= nd))
67       error ("mean: DIM must be an integer and a valid dimension");
68     endif
69   endif
70
71   y = sumsq (x, dim) / sz(dim);
72
73 endfunction
74
75
76 %!assert(meansq (1:5), 11);
77 %!assert(meansq (single(1:5)), single(11));
78 %!assert(meansq (magic (4)), [94.5, 92.5, 92.5, 94.5]);
79 %!assert(meansq (magic (4), 2), [109.5; 77.5; 77.5; 109.5]);
80
81 %% Test input validation
82 %!error meansq ()
83 %!error meansq (1, 2, 3)
84 %!error meansq (['A'; 'B']);
85 %!error meansq (1, ones(2,2))
86 %!error meansq (1, 1.5)
87 %!error meansq (1, 0)
88 %!error meansq (1, 3)
89