5410
|
1 ## Copyright (C) 1995, 1996, 1997 Kurt Hornik |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
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 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
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. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
5411
|
21 ## @deftypefn {Function File} {} gaminv (@var{x}, @var{a}, @var{b}) |
5410
|
22 ## For each component of @var{x}, compute the quantile (the inverse of |
|
23 ## the CDF) at @var{x} of the Gamma distribution with parameters @var{a} |
5642
|
24 ## and @var{b}. |
|
25 ## @seealso{gamma, gammaln, gammainc, gampdf, gamcdf, gamrnd} |
5410
|
26 ## @end deftypefn |
|
27 |
5428
|
28 ## Author: KH <Kurt.Hornik@wu-wien.ac.at> |
5410
|
29 ## Description: Quantile function of the Gamma distribution |
|
30 |
5411
|
31 function inv = gaminv (x, a, b) |
5410
|
32 |
|
33 if (nargin != 3) |
6046
|
34 print_usage (); |
5410
|
35 endif |
|
36 |
|
37 if (!isscalar (a) || !isscalar(b)) |
|
38 [retval, x, a, b] = common_size (x, a, b); |
|
39 if (retval > 0) |
5411
|
40 error ("gaminv: x, a and b must be of common size or scalars"); |
5410
|
41 endif |
|
42 endif |
|
43 |
|
44 sz = size (x); |
|
45 inv = zeros (sz); |
|
46 |
|
47 k = find ((x < 0) | (x > 1) | isnan (x) | !(a > 0) | !(b > 0)); |
|
48 if (any (k)) |
|
49 inv (k) = NaN; |
|
50 endif |
|
51 |
|
52 k = find ((x == 1) & (a > 0) & (b > 0)); |
|
53 if (any (k)) |
|
54 inv (k) = Inf; |
|
55 endif |
|
56 |
|
57 k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0)); |
|
58 if (any (k)) |
|
59 if (!isscalar(a) || !isscalar(b)) |
|
60 a = a (k); |
|
61 b = b (k); |
6777
|
62 y = a .* b; |
5410
|
63 else |
6777
|
64 y = a * b * ones (size (k)); |
5410
|
65 endif |
|
66 x = x (k); |
|
67 l = find (x < eps); |
|
68 if (any (l)) |
|
69 y(l) = sqrt (eps) * ones (length (l), 1); |
|
70 endif |
|
71 |
|
72 y_old = y; |
|
73 for i = 1 : 100 |
5411
|
74 h = (gamcdf (y_old, a, b) - x) ./ gampdf (y_old, a, b); |
5410
|
75 y_new = y_old - h; |
|
76 ind = find (y_new <= eps); |
|
77 if (any (ind)) |
|
78 y_new (ind) = y_old (ind) / 10; |
|
79 h = y_old - y_new; |
|
80 endif |
|
81 if (max (abs (h)) < sqrt (eps)) |
|
82 break; |
|
83 endif |
|
84 y_old = y_new; |
|
85 endfor |
|
86 |
|
87 inv (k) = y_new; |
|
88 endif |
|
89 |
|
90 endfunction |