1 ## Copyright (C) 2009 Soren Hauberg <soren@hauberg.org>
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
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
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/>.
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}.
22 ## The Von Mises distribution has probability density function
24 ## f (@var{x}) = exp (@var{k} * cos (@var{x} - @var{mu})) / @var{Z} ,
26 ## where @var{Z} is a normalisation constant.
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
34 function theta = vmrnd (mu = 0, k = 1, sz = 1)
37 error ("vmrnd: first input must be a scalar");
40 if (!isreal (k) || k <= 0)
41 error ("vmrnd: second input must be a real positive scalar");
46 elseif (!isvector (sz))
47 error ("vmrnd: third input must be a scalar or a vector");
52 ## k is small: sample uniformly on circle
53 theta = 2 * pi * rand (sz) - pi;
56 a = 1 + sqrt (1 + 4 * k.^2);
57 b = (a - sqrt (2 * a)) / (2 * k);
58 r = (1 + b^2) / (2 * b);
61 notdone = true (N, 1);
63 u (:, notdone) = rand (3, N);
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));
69 notdone = (u (2, :) >= c .* (2 - c)) & (log (c) - log (u (2, :)) + 1 - c < 0);
73 theta = mu + sign (u (3, :) - 0.5) .* acos (f);
74 theta = reshape (theta, sz);