Personal tools
You are here: Home Examples Utility functions Generating random sparse matrices
Document Actions

Generating random sparse matrices

A Python function for random generation of sparse matrices with a specified density

Click here to get the file

Size 1 kB - File type text/python-source

File 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))
 

Powered by Plone CMS, the Open Source Content Management System