3200
|
1 ## Copyright (C) 1995, 1996, 1997 Kurt Hornik |
3426
|
2 ## |
3200
|
3 ## This program is free software; you can redistribute it and/or modify |
|
4 ## it under the terms of the GNU General Public License as published by |
|
5 ## the Free Software Foundation; either version 2, or (at your option) |
|
6 ## any later version. |
3426
|
7 ## |
3200
|
8 ## This program is distributed in the hope that it will be useful, but |
|
9 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
3426
|
11 ## General Public License for more details. |
|
12 ## |
3200
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this file. If not, write to the Free Software Foundation, |
|
15 ## 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
|
16 |
3367
|
17 ## -*- texinfo -*- |
|
18 ## @deftypefn {Function File} {} mean (@var{x}, @var{opt}) |
|
19 ## If @var{x} is a vector, compute the mean of the elements of @var{x} |
|
20 ## @iftex |
|
21 ## @tex |
|
22 ## $$ {\rm mean}(x) = \bar{x} = {1\over N} \sum_{i=1}^N x_i $$ |
|
23 ## @end tex |
|
24 ## @end iftex |
|
25 ## @ifinfo |
3426
|
26 ## |
3367
|
27 ## @example |
|
28 ## mean (x) = SUM_i x(i) / N |
|
29 ## @end example |
|
30 ## @end ifinfo |
|
31 ## If @var{x} is a matrix, compute the mean for each column and return them |
|
32 ## in a row vector. |
3200
|
33 ## |
3367
|
34 ## With the optional argument @var{opt}, the kind of mean computed can be |
|
35 ## selected. The following options are recognized: |
|
36 ## |
|
37 ## @table @code |
|
38 ## @item "a" |
|
39 ## Compute the (ordinary) arithmetic mean. This is the default. |
|
40 ## |
|
41 ## @item "g" |
|
42 ## Computer the geometric mean. |
|
43 ## |
|
44 ## @item "h" |
|
45 ## Compute the harmonic mean. |
|
46 ## @end table |
|
47 ## @end deftypefn |
3426
|
48 |
3200
|
49 ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at> |
|
50 ## Description: Compute arithmetic, geometric, and harmonic mean |
|
51 |
|
52 function y = mean (x, opt) |
|
53 |
|
54 if ((nargin < 1) || (nargin > 2)) |
|
55 usage ("mean (x [, opt])"); |
|
56 endif |
|
57 |
|
58 if isempty (x) |
|
59 error ("mean: x must not be empty"); |
|
60 endif |
3426
|
61 |
3200
|
62 if (rows (x) == 1) |
3265
|
63 x = x.'; |
3200
|
64 endif |
3426
|
65 |
3200
|
66 if (nargin == 1) |
|
67 opt = "a"; |
|
68 endif |
|
69 |
|
70 [r, c] = size (x); |
3426
|
71 |
3200
|
72 if (strcmp (opt, "a")) |
|
73 y = sum (x) / r; |
|
74 elseif (strcmp (opt, "g")) |
|
75 y = NaN * ones (1, c); |
|
76 i = find (all (x > 0)); |
|
77 if any (i) |
|
78 y(i) = exp (sum (log (x(:, i))) / r); |
|
79 endif |
|
80 elseif (strcmp (opt, "h")) |
|
81 y = NaN * ones (1, c); |
|
82 i = find (all (x != 0)); |
|
83 if any (i) |
|
84 y(i) = r ./ sum (1 ./ x(:, i)); |
|
85 endif |
|
86 else |
|
87 error (sprintf ("mean: option `%s' not recognized", opt)); |
|
88 endif |
3426
|
89 |
3200
|
90 endfunction |