diff scripts/sparse/sprandn.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 bae887ebea48
children 72c96de7a403
line wrap: on
line diff
--- a/scripts/sparse/sprandn.m	Wed Sep 21 21:37:12 2011 -0500
+++ b/scripts/sparse/sprandn.m	Fri Sep 23 02:40:05 2011 -0500
@@ -27,68 +27,30 @@
 ## @var{d} should be between 0 and 1. Values will be normally
 ## distributed with mean of zero and variance 1.
 ##
-## Note: sometimes the actual density may be a bit smaller than @var{d}.
-## This is unlikely to happen for large really sparse matrices.
-##
 ## If called with a single matrix argument, a random sparse matrix is
 ## generated wherever the matrix @var{S} is non-zero.
-## @seealso{sprand}
+## @seealso{sprand, sprandsym}
 ## @end deftypefn
 
 ## Author: Paul Kienzle <pkienzle@users.sf.net>
 
 function S = sprandn (m, n, d)
 
-  if (nargin != 1 && nargin != 3)
+  if (nargin == 1 )
+    S = __sprand_impl__ (m, @randn);
+  elseif ( nargin == 3)
+    S = __sprand_impl__ (m, n, d, "sprandn", @randn);
+  else
     print_usage ();
   endif
 
-  if (nargin == 1)
-    [i, j] = find (m);
-    [nr, nc] = size (m);
-    S = sparse (i, j, randn (size (i)), nr, nc);
-    return;
-  endif
-
-  if (!(isscalar (m) && m == fix (m) && m > 0))
-    error ("sprand: M must be an integer greater than 0");
-  endif
-
-  if (!(isscalar (n) && n == fix (n) && n > 0))
-    error ("sprand: N must be an integer greater than 0");
-  endif
-
-  if (d < 0 || d > 1)
-    error ("sprand: density D must be between 0 and 1");
-  endif
-
-  mn = m*n;
-  k = round (d*mn);
-  idx = unique (fix (rand (min (k*1.01, k+10), 1) * mn)) + 1;
-  ## idx contains random numbers in [1,mn]
-  ## generate 1% or 10 more random values than necessary in order to
-  ## reduce the probability that there are less than k distinct
-  ## values; maybe a better strategy could be used but I don't think
-  ## it's worth the price.
-
-  ## actual number of entries in S
-  k = min (length (idx), k);
-  j = floor ((idx(1:k)-1)/m);
-  i = idx(1:k) - j*m;
-  if (isempty (i))
-    S = sparse (m, n);
-  else
-    S = sparse (i, j+1, randn (k, 1), m, n);
-  endif
-
 endfunction
 
 
-## FIXME: Test for density can't happen until code of sprandn is improved
 %!test
 %! s = sprandn (4, 10, 0.1);
 %! assert (size (s), [4, 10]);
-##%! assert (nnz (s) / numel (s), 0.1, .01);
+%! assert (nnz (s) / numel (s), 0.1);
 
 %% Test 1-input calling form
 %!test