Sparse Matrices

Scipy is very good at dealing with sparse matrices. Let’s demonstrate it by showing how easy it is to create our first sparse matrix.

Creating a sparse matrix

//

from numpy import *

from scipy import sparse
a=numpy.array([[1,0,2],[0,3,0]])
m=sparse.lil_matrix(a)

m=sparse.lil_matrix( [ array( [ 10.0 , 100.0 , 1000.0 ] ) ] ) # singleton array of array == row matrix

#2)
A = lil_matrix((3, 3))
A[0,:]=rand(3) ; A[1,:]=rand(3) ; A[2,:]=rand(3) # ran(3) == numpy.array([ 0.78117298, 0.27225199, 0.39260483])

#3)
A=lil_matrix((3, 1)
A[0,0]=1 ; A=[1,0]=2 ; A[2,0]=3

Mutiplying Two Sparse Matrices
# first matrix
A = lil_matrix((3, 3))
A[0,:]=rand(3)
A[1,:]=rand(3)
A[2,:]=rand(3)
==> matrix([[ 0.87069596, 0.09936564, 0.53200116],
[ 0.96187027, 0.18599277, 0.37201974],
[ 0.03840103, 0.25979662, 0.63057508]])

# second matrix
B=lil_matrix((3, 1)
B[0,0]=1 ; B[1,0]=2 ; B[2,0]=3

# multiply
C= A *B

Matrix Transposition
tab=numpy.array([[1,0,2],[0,3,0]])
A=sparse.lil_matrix(tab)
A=A.tocsc()
print A.todense()
At=A.transpose()
print At.todense()

Advertisements
%d bloggers like this: