5164
|
1 ## Copyright (C) 2004 Paul Kienzle |
|
2 ## |
|
3 ## This program is free software and is in the public domain |
|
4 |
|
5 ## -*- texinfo -*- |
5610
|
6 ## @deftypefn {Function File} {} sprandn (@var{m}, @var{n}, @var{d}) |
|
7 ## @deftypefnx {Function File} {} sprandn (@var{s}) |
5164
|
8 ## Generate a random sparse matrix. The size of the matrix will be |
|
9 ## @var{m} by @var{n}, with a density of values given by @var{d}. |
|
10 ## @var{d} should be between 0 and 1. Values will be normally |
|
11 ## distributed with mean of zero and variance 1. |
|
12 ## |
|
13 ## Note: sometimes the actual density may be a bit smaller than @var{d}. |
|
14 ## This is unlikely to happen for large really sparse matrices. |
|
15 ## |
|
16 ## If called with a single matrix argument, a random sparse matrix is |
|
17 ## generated wherever the matrix @var{S} is non-zero. |
5642
|
18 ## @seealso{sprand} |
5164
|
19 ## @end deftypefn |
|
20 |
|
21 ## This program is public domain |
|
22 ## Author: Paul Kienzle <pkienzle@users.sf.net> |
|
23 |
|
24 function S = sprandn(m,n,d) |
|
25 if nargin == 1 |
|
26 [i,j,v,nr,nc] = spfind(m); |
|
27 S = sparse(i,j,randn(size(v)),nr,nc); |
|
28 elseif nargin == 3 |
|
29 mn = m*n; |
|
30 k = round(d*mn); |
|
31 idx=unique(fix(rand(min(k*1.01,k+10),1)*mn))+1; |
|
32 # idx contains random numbers in [1,mn] |
|
33 # generate 1% or 10 more random values than necessary |
|
34 # in order to reduce the probability that there are less than k |
|
35 # distinct values; |
|
36 # maybe a better strategy could be used |
|
37 # but I don't think it's worth the price |
|
38 k = min(length(idx),k); # actual number of entries in S |
|
39 j = floor((idx(1:k)-1)/m); |
|
40 i = idx(1:k) - j*m; |
|
41 if isempty(i) |
|
42 S = sparse(m,n); |
|
43 else |
|
44 S = sparse(i,j+1,randn(k,1),m,n); |
|
45 endif |
|
46 else |
6046
|
47 print_usage (); |
5164
|
48 endif |
|
49 endfunction |