0% found this document useful (0 votes)
5 views3 pages

Practical 4

Uploaded by

yjgaming131121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Practical 4

Uploaded by

yjgaming131121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#Practical 4: Array/List

Q 1: Create sparse matrix & display its transpose in python

#sparse matrix implementation in python [Create & Transpose ]

import numpy as np
from scipy.sparse import csr_matrix

a=np.array([[1,0,0],[0,0,4],[0,2,0]])
sm=csr_matrix(a)

print("\nThe simple matrix is: ")


print(a)
print("\n The equivalent csr sparce matrix is")
print(sm)

#sparse matrix transpose

b=sm.transpose().tocsr()

print("Transposed matrix is: ")


print(b)
Output:

The simple matrix is:


[[1 0 0]
[0 0 4]
[0 2 0]]

The equivalent csr sparce matrix is


<Compressed Sparse Row sparse matrix of dtype 'int64'
with 3 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(1, 2) 4
(2, 1) 2
Transposed matrix is:
<Compressed Sparse Row sparse matrix of dtype 'int64'
with 3 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(1, 2) 2
(2, 1) 4
Q2. Create a python program for addition of 2 sparse matrices

#sparse matrix implementation in python [Create & Transpose ]

import numpy as np
from scipy.sparse import csr_matrix

a=np.array([[1,0,0],[0,0,4],[0,2,0]])
b=np.array([[0,0,1],[0,0,0],[0,3,0]])
sm1=csr_matrix(a)
sm2=csr_matrix(b)

print("\nThe First simple matrix is: ")


print(a)
print("\n The equivalent csr sparce matrix is")
print(sm1)

print("\nThe Second simple matrix is: ")


print(b)
print("\n The equivalent csr sparce matrix is")
print(sm2)

#addition

c=sm1+sm2

print("\nAddition of sparse matrices is: ")


print(c)

Output:

The First simple matrix is:


[[1 0 0]
[0 0 4]
[0 2 0]]

The equivalent csr sparce matrix is


<Compressed Sparse Row sparse matrix of dtype 'int64'
with 3 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(1, 2) 4
(2, 1) 2

The Second simple matrix is:


[[0 0 1]
[0 0 0]
[0 3 0]]

The equivalent csr sparce matrix is


<Compressed Sparse Row sparse matrix of dtype 'int64'
with 2 stored elements and shape (3, 3)>
Coords Values
(0, 2) 1
(2, 1) 3

Addition of sparse matrices is:


<Compressed Sparse Row sparse matrix of dtype 'int64'
with 4 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(0, 2) 1
(1, 2) 4
(2, 1) 5

You might also like