[SciPy-user] Random sparse matrices

Nathan Bell wnbell@gmail....
Tue Apr 22 13:08:15 CDT 2008


On Tue, Apr 22, 2008 at 12:26 PM, Mico Filós <elmico.filos@gmail.com> wrote:
>  Could anyone suggest a hint of how to get a random sparse matrix
>  without reinventing the wheel (using numpy/scipy functions whenever
>  possible).

Here's a first stab at it.


from numpy.random import random_integers
from scipy import rand, randn, ones
from scipy.sparse import csr_matrix

def _rand_sparse(m, n, density):
    # check parameters here

    nnz = max( min( int(m*n*density), m*n), 0)

    row  = random_integers(low=0, high=m-1, size=nnz)
    col  = random_integers(low=0, high=n-1, size=nnz)
    data = ones(nnz, dtype='int8')

    # duplicate (i,j) entries will be summed together
    return csr_matrix( (data,(row,col)), shape=(m,n) )


def sprand(m, n, density):
    """Document me"""
    A = _rand_sparse(m, n, density)
    A.data = rand(A.nnz)
    return A

def sprandn(m, n, density):
    """Document me"""
    A = _rand_sparse(m, n, density)
    A.data = randn(A.nnz)
    return A


if __name__ == '__main__':
    print sprand(4, 3, 0.5).todense()
    print sprandn(4, 3, 0.5).todense()



>  Is there any reason why 'sprandn' does not exist? (I mean, perhaps
>  there is a more general method to do that, I don't know).

Simply a lack of time :)

If you (or someone else) would add the appropriate docstrings and
error checking then I'd happily add these functions to scipy.sparse.


-- 
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/


More information about the SciPy-user mailing list