]> Creatis software - CreaPhase.git/blob - octave_packages/statistics-1.1.3/vmrnd.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / statistics-1.1.3 / vmrnd.m
1 ## Copyright (C) 2009 Soren Hauberg <soren@hauberg.org>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} @var{theta} = vmrnd (@var{mu}, @var{k})
18 ## @deftypefnx{Function File} @var{theta} = vmrnd (@var{mu}, @var{k}, @var{sz})
19 ## Draw random angles from a Von Mises distribution with mean @var{mu} and
20 ## concentration @var{k}.
21 ##
22 ## The Von Mises distribution has probability density function
23 ## @example
24 ## f (@var{x}) = exp (@var{k} * cos (@var{x} - @var{mu})) / @var{Z} ,
25 ## @end example
26 ## where @var{Z} is a normalisation constant.
27 ##
28 ## The output, @var{theta}, is a matrix of size @var{sz} containing random angles
29 ## drawn from the given Von Mises distribution. By default, @var{mu} is 0
30 ## and @var{k} is 1.
31 ## @seealso{vmpdf}
32 ## @end deftypefn
33
34 function theta = vmrnd (mu = 0, k = 1, sz = 1)
35   ## Check input
36   if (!isreal (mu))
37     error ("vmrnd: first input must be a scalar");
38   endif
39   
40   if (!isreal (k) || k <= 0)
41     error ("vmrnd: second input must be a real positive scalar");
42   endif
43   
44   if (isscalar (sz))
45     sz = [sz, sz];
46   elseif (!isvector (sz))
47     error ("vmrnd: third input must be a scalar or a vector");
48   endif
49   
50   ## Simulate!
51   if (k < 1e-6)
52     ## k is small: sample uniformly on circle
53     theta = 2 * pi * rand (sz) - pi;
54   
55   else
56     a = 1 + sqrt (1 + 4 * k.^2);
57     b = (a - sqrt (2 * a)) / (2 * k);
58     r = (1 + b^2) / (2 * b);
59
60     N = prod (sz);
61     notdone = true (N, 1);
62     while (any (notdone))
63       u (:, notdone) = rand (3, N);
64       
65       z (notdone) = cos (pi * u (1, notdone));
66       f (notdone) = (1 + r * z (notdone)) ./ (r + z (notdone));
67       c (notdone) = k * (r - f (notdone));
68       
69       notdone = (u (2, :) >= c .* (2 - c)) & (log (c) - log (u (2, :)) + 1 - c < 0);
70       N = sum (notdone);
71     endwhile
72     
73     theta = mu + sign (u (3, :) - 0.5) .* acos (f);
74     theta = reshape (theta, sz);
75   endif
76 endfunction