5164
|
1 ## Copyright (C) 2004 Paul Kienzle |
|
2 ## |
|
3 ## This program is free software and is in the public domain |
|
4 |
|
5 ## -*- texinfo -*- |
|
6 ## @deftypefn {Function File} {} sprand (@var{m}, @var{n}, @var{d}) |
|
7 ## @deftypefnx {Function File} {} sprand (@var{s}) |
|
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}. |
5610
|
10 ## @var{d} should be between 0 and 1. Values will be uniformly |
|
11 ## distributed between 0 and 1. |
5164
|
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{sprandn} |
5164
|
19 ## @end deftypefn |
|
20 |
|
21 ## This program is public domain |
|
22 ## Author: Paul Kienzle <pkienzle@users.sf.net> |
|
23 ## |
|
24 ## Changelog: |
|
25 ## |
|
26 ## Piotr Krzyzanowski <przykry2004@users.sf.net> |
|
27 ## 2004-09-27 use Paul's hint to allow larger random matrices |
|
28 ## at the price of sometimes lower density than desired |
|
29 ## David Bateman |
|
30 ## 2004-10-20 Texinfo help and copyright message |
|
31 |
|
32 function S = sprand (m, n, d) |
|
33 if nargin == 1 |
|
34 [i,j,v,nr,nc] = spfind(m); |
|
35 S = sparse (i,j,rand(size(v)),nr,nc); |
|
36 elseif nargin == 3 |
|
37 mn = n*m; |
|
38 k = round(d*mn); # how many entries in S would be satisfactory? |
|
39 idx=unique(fix(rand(min(k*1.01,k+10),1)*mn))+1; |
|
40 # idx contains random numbers in [1,mn] |
|
41 # generate 1% or 10 more random values than necessary |
|
42 # in order to reduce the probability that there are less than k |
|
43 # distinct values; |
|
44 # maybe a better strategy could be used |
|
45 # but I don't think it's worth the price |
|
46 k = min(length(idx),k); # actual number of entries in S |
|
47 j = floor((idx(1:k)-1)/m); |
|
48 i = idx(1:k) - j*m; |
|
49 if isempty(i) |
|
50 S = sparse(m,n); |
|
51 else |
|
52 S = sparse(i,j+1,rand(k,1),m,n); |
|
53 endif |
|
54 else |
|
55 usage("sprand(m,n,density) OR sprand(S)"); |
|
56 endif |
|
57 endfunction |