Tuesday, March 25, 2014

Generating a Random m x n sparse matrix in python with given number of ones

A friend of mine Sheraz needed a small code chunk in python that could generate a random sparse matrix. The requirement was to be able to generate a m by n matrix where most of the entries are 0's and the user mentions the number of 1's required. I am listing down the code that was written by me and later improved by Sheraz for the purpose of preserving it by making it accessible online. The function genmatrix takes 3 arguments en is required number of 1's, s and n correspond to the number of rows and columns of matrix a

from numpy import *
from random import *
from math import *

def genmatrix(en,s, n):
    count=0
    S=range(s)
    N=range(n)   
    a = zeros(shape=(s,n))
    while (count < en):
        i= randint(0,s-1)
        j= randint(0,n-1)
        print i, j
        if (i in S) and (j in N):
            a[(i,j)]=1
            S.remove(i)
            N.remove(j)
            count +=1
    #print a
    #print [sum(a[i]) for i in range(s)]
    #print [sum(a[:,i]) for i in range(n)]
    return a 

No comments:

Post a Comment