Generating random sparse matrices
A Python function for random generation of sparse matrices with a specified density
Size 1 kB - File type text/python-sourceFile contents
from cvxopt.base import matrix, spmatrix
from cvxopt.base import normal
import random
def sp_rand(m,n,a):
'''
Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.
'''
if m == 0 or n == 0: return spmatrix([], [], [], (m,n))
nnz = min(max(0, int(round(a*m*n))), m*n)
nz = matrix(random.sample(xrange(m*n), nnz), tc='i')
return spmatrix(normal(nnz,1), nz%m, nz/m, (m,n))
Click here to get the file