]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/distributions/laplace_rnd.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / distributions / laplace_rnd.m
1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 1995-2012 Kurt Hornik
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} {} laplace_rnd (@var{r})
22 ## @deftypefnx {Function File} {} laplace_rnd (@var{r}, @var{c}, @dots{})
23 ## @deftypefnx {Function File} {} laplace_rnd ([@var{sz}])
24 ## Return a matrix of random samples from the Laplace distribution.
25 ##
26 ## When called with a single size argument, return a square matrix with
27 ## the dimension specified.  When called with more than one scalar argument the
28 ## first two arguments are taken as the number of rows and columns and any
29 ## further arguments specify additional matrix dimensions.  The size may also
30 ## be specified with a vector of dimensions @var{sz}.
31 ## @end deftypefn
32
33 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
34 ## Description: Random deviates from the Laplace distribution
35
36 function rnd = laplace_rnd (varargin)
37
38   if (nargin < 1)
39     print_usage ();
40   endif
41
42   if (nargin == 1)
43     if (isscalar (varargin{1}) && varargin{1} >= 0)
44       sz = [varargin{1}, varargin{1}];
45     elseif (isrow (varargin{1}) && all (varargin{1} >= 0))
46       sz = varargin{1}(:)';
47     else
48       error ("laplace_rnd: dimension vector must be row vector of non-negative integers");
49     endif
50   elseif (nargin > 1)
51     if (any (cellfun (@(x) (!isscalar (x) || x < 0), varargin)))
52       error ("laplace_rnd: dimensions must be non-negative integers");
53     endif
54     sz = [varargin{:}];
55   endif
56
57   tmp = rand (sz);
58   rnd = (tmp < 1/2) .* log (2 * tmp) - (tmp > 1/2) .* log (2 * (1 - tmp));
59
60 endfunction
61
62
63 %!assert(size (laplace_rnd (3)), [3, 3]);
64 %!assert(size (laplace_rnd ([4 1])), [4, 1]);
65 %!assert(size (laplace_rnd (4,1)), [4, 1]);
66
67 %% Test input validation
68 %!error laplace_rnd ()
69 %!error laplace_rnd (-1)
70 %!error laplace_rnd (ones(2))
71 %!error laplace_rnd ([2 -1 2])
72 %!error laplace_rnd (1, ones(2))
73 %!error laplace_rnd (1, -1)
74