Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Practical 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

#Practical 3: Array/List

Q 1: Create Matrix using numpy module & do matrix operations (addition,Subtraction,Multiplication


& transpose) in python

import numpy as np

a=np.array([[1,2,3],[4,5,6],[7,8,9]])

b=np.array([[1,2,1],[4,3,2],[6,3,2]])

print("\nMatrix1: ")

print(a)

print("\nMatrix2: ")

print(b)

#matrix addition

c=a+b

print("\nMatrix addition is: ")

print(c)

#matrix Subtraction

d=a-b

print("\nMatrix Subtraction is: ")

print(d)

#matrix Multiplication

e=a@b

print("\nMatrix Multiplication is: ")

print(e)
#matrix transpose

t=a.transpose()

print("\nTranspose of Matrix a is: ")

print(t)

Output:

Matrix 1:

[[1 2 3]

[4 5 6]

[7 8 9]]

Matrix 2:

[[1 2 1]

[4 3 2]

[6 3 2]]

Matrix addition is:

[[ 2 4 4]

[ 8 8 8]

[13 11 11]]

Matrix Subtraction is:

[[0 0 2]

[0 2 4]

[1 5 7]]

Matrix Multiplication is:

[[27 17 11]

[60 41 26]

[93 65 41]]

Transpose of Matrix a is:


[[1 4 7]

[2 5 8]

[3 6 9]]

#Q 2: Create Sparse Matrix using scipy.sparse module & apply different methods

import numpy as np

from scipy.sparse import csr_array

#Creating Normal 2-D array using numpy module


A=np.array([[1,2,0],[0,0,0],[0,0,2]])

#Converting to sparse matrix


SA=csr_array(A)

print("Original Matrix is:\n ");

print(A)

print("\nThe equivalent sparse matrix is:\n")

print(SA)

#Apply properties & method on sparse matrix

#Viewing stored data (not the zero items) with the data property:
print("Data in the sparse matrix is : ",SA.data)

#Counting nonzeros with the count_nonzero() method:


print("Number of Non-zero elements is :",SA.count_nonzero())

#Converting from csr to csc with the tocsc() method:


new_mat=SA.tocsc()

print("\nEquivalent CSC matrix is: ",new_mat)

Output:
Original Matrix is:

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

The equivalent sparse matrix is:

<Compressed Sparse Row sparse array of dtype 'int64'


with 3 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(0, 1) 2
(2, 2) 2
Data in the sparse matrix is : [1 2 2]
Number of Non-zero elements is : 3

Equivalent CSC matrix is: <Compressed Sparse Column sparse array of dtype 'int64'
with 3 stored elements and shape (3, 3)>
Coords Values
(0, 0) 1
(0, 1) 2
(2, 2) 2

You might also like