# [SciPy-user] Random sparse matrices

Nils Wagner nwagner@iam.uni-stuttgart...
Fri Apr 25 15:14:53 CDT 2008

```On Fri, 25 Apr 2008 22:04:00 +0200
"Anne Archibald" <peridot.faceted@gmail.com> wrote:
> On 25/04/2008, Nathan Bell <wnbell@gmail.com> wrote:
>> On Fri, Apr 25, 2008 at 9:17 AM, Mico Filós
>><elmico.filos@gmail.com> wrote:
>>  > Dear all,
>>  >
>>  >  here is my first attempt. I basically use Nathan's
>>suggested
>>  >  functions, and _rand_sparse incorporates the
>>algorithm proposed by
>>  >  David to avoid ending up with fewer nonzero elements
>>than expected. It
>>  >  is the first time I propose an update
>>  >  for scipy code, so be lenient with me :)
>>
>>
>> Thanks for your contribution Mico.  Unfortunately, the
>>line
>>
>>    rand_seq = permutation(m*n)[:nnz]
>>
>> is a *dense* MxN operation, so we cannot use this
>>approach.
>>
>>  MATLAB's sprand() and sprandn() have the same artifact
>>as the code I
>>  presented, so I don't know whether it's worth trying to
>>avoid the
>>  duplicate entries.
>>
>>  If you can figure out an economial way to produce
>>exactly nnz elements
>>  in the result, then we would probably use it.  I wasn't
>>able to come
>>  up with anything better than the MATLAB approach.
>
> Here's an approach that works. Not ideal, but still only
>O(nnz): pick
> nnz distinct integers. Throw out any repeats and pick
>replacements.
> Repeat until you have no repeats. Requires an average of
>just a few
> iterations unless nnz>(m*n)/2 (say), in which case you
>can safely just
> use permutation().
>
> Anne

Hi Anne,

I run your script several times. Sometimes I get
>>> sprandn(5,5,3).todense()
matrix([[ 0.        ,  0.        ,  0.        ,  0.
,  0.        ],
[ 0.        ,  0.36548958,  0.        ,  0.
,  0.        ],
[ 1.51125878,  0.        ,  0.        ,  0.
, -0.20285678],
[ 0.        ,  0.        ,  0.        ,  0.
,  0.        ],
[ 0.        ,  0.        ,  0.        ,  0.
,  0.        ]])
>>> sprandn(5,5,3).todense()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "sprand.py", line 23, in sprandn
return
scipy.sparse.coo_matrix((np.random.randn(nnz),ij),(m,n))
File
"/usr/lib/python2.4/site-packages/scipy/sparse/coo.py",
line 180, in __init__
self._check()
File
"/usr/lib/python2.4/site-packages/scipy/sparse/coo.py",
line 213, in _check
raise ValueError, "row index exceedes matrix
dimensions"
ValueError: row index exceedes matrix dimensions

Cheers,
Nils
```