comparison scripts/sparse/sprand.m @ 13197:6db186dfdeaa

Refactor sprandn/sprand code, move common code to common function (bug #34352) * __sprand_impl__.m: New file * module.mk: Add new file * sprand.m: Remove comment in docstring about inaccuracy of density. Put sprandsym in @seealso. Refactor repeated code into __sprand_impl__.m * sprandn.m: Ditto. Also enable test for exact density.
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Fri, 23 Sep 2011 02:40:05 -0500
parents 5976ba269538
children 72c96de7a403
comparison
equal deleted inserted replaced
13196:5976ba269538 13197:6db186dfdeaa
25 ## Generate a random sparse matrix. The size of the matrix will be 25 ## Generate a random sparse matrix. The size of the matrix will be
26 ## @var{m} by @var{n}, with a density of values given by @var{d}. 26 ## @var{m} by @var{n}, with a density of values given by @var{d}.
27 ## @var{d} should be between 0 and 1. Values will be uniformly 27 ## @var{d} should be between 0 and 1. Values will be uniformly
28 ## distributed between 0 and 1. 28 ## distributed between 0 and 1.
29 ## 29 ##
30 ## Note: sometimes the actual density may be a bit smaller than @var{d}.
31 ## This is unlikely to happen for large, truly sparse, matrices.
32 ##
33 ## If called with a single matrix argument, a random sparse matrix is 30 ## If called with a single matrix argument, a random sparse matrix is
34 ## generated wherever the matrix @var{S} is non-zero. 31 ## generated wherever the matrix @var{S} is non-zero.
35 ## @seealso{sprandn} 32 ## @seealso{sprandn, sprandsym}
36 ## @end deftypefn 33 ## @end deftypefn
37 34
38 ## Author: Paul Kienzle <pkienzle@users.sf.net> 35 ## Author: Paul Kienzle <pkienzle@users.sf.net>
39 ## 36 ##
40 ## Changelog: 37 ## Changelog:
45 ## David Bateman 42 ## David Bateman
46 ## 2004-10-20 Texinfo help and copyright message 43 ## 2004-10-20 Texinfo help and copyright message
47 44
48 function S = sprand (m, n, d) 45 function S = sprand (m, n, d)
49 46
50 if (nargin != 1 && nargin != 3) 47 if (nargin == 1 )
48 S = __sprand_impl__ (m, @rand);
49 elseif ( nargin == 3)
50 S = __sprand_impl__ (m, n, d, "sprand", @rand);
51 else
51 print_usage (); 52 print_usage ();
52 endif 53 endif
53
54 if (nargin == 1)
55 [i, j] = find (m);
56 [nr, nc] = size (m);
57 S = sparse (i, j, rand (size (i)), nr, nc);
58 return;
59 endif
60
61 if (!(isscalar (m) && m == fix (m) && m > 0))
62 error ("sprand: M must be an integer greater than 0");
63 endif
64
65 if (!(isscalar (n) && n == fix (n) && n > 0))
66 error ("sprand: N must be an integer greater than 0");
67 endif
68
69 if (d < 0 || d > 1)
70 error ("sprand: density D must be between 0 and 1");
71 endif
72
73 mn = m*n;
74 ## how many entries in S would be satisfactory?
75 k = round (d*mn);
76 idx = randperm (mn, k);
77
78 [i, j] = ind2sub ([m, n], idx);
79 S = sparse (i, j, rand (k, 1), m, n);
80 54
81 endfunction 55 endfunction
82 56
83 %!test 57 %!test
84 %! s = sprand (4, 10, 0.1); 58 %! s = sprand (4, 10, 0.1);