]> Creatis software - CreaPhase.git/blob - octave_packages/m/sparse/private/__sprand_impl__.m
update packages
[CreaPhase.git] / octave_packages / m / sparse / private / __sprand_impl__.m
1 ## Copyright (C) 2004-2012 Paul Kienzle
2 ## Copyright (C) 2012 Jordi GutiĆ©rrez Hermoso
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 ## Original version by Paul Kienzle distributed as free software in the
21 ## public domain.
22
23 ## -*- texinfo -*-
24 ## @deftypefn  {Function File} {} __sprand_impl__ (@var{s}, @var{randfun})
25 ## @deftypefnx {Function File} {} __sprand_impl__ (@var{m}, @var{n}, @var{d}, @var{funname}, @var{randfun})
26 ## Undocumented internal function.
27 ## @end deftypefn
28
29 ## Actual implementation of sprand and sprandn happens here.
30
31 function S = __sprand_impl__ (varargin)
32
33   if (nargin == 2)
34     m = varargin{1};
35     randfun = varargin{2};
36     [i, j] = find (m);
37     [nr, nc] = size (m);
38     S = sparse (i, j, randfun (size (i)), nr, nc);
39     return;
40   endif
41
42   [m, n, d, funname, randfun] = deal(varargin{:});
43
44   if (!(isscalar (m) && m == fix (m) && m > 0))
45     error ("%s: M must be an integer greater than 0", funname);
46   endif
47
48   if (!(isscalar (n) && n == fix (n) && n > 0))
49     error ("%s: N must be an integer greater than 0", funname);
50   endif
51
52   if (d < 0 || d > 1)
53     error ("%s: density D must be between 0 and 1", funname);
54   endif
55
56   mn = m*n;
57   k = round (d*mn);
58   idx = randperm (mn, k);
59
60   [i, j] = ind2sub ([m, n], idx);
61   S = sparse (i, j, randfun (k, 1), m, n);
62
63 endfunction