0% found this document useful (0 votes)
4 views34 pages

#C

The document contains a series of practical exercises involving matrix operations in Python, including accepting matrices from user input, displaying transposes, finding determinants, and performing arithmetic operations like addition and multiplication. It also checks for the existence of inverses for 2x2 and 3x3 matrices based on their determinants. Each exercise is structured with code snippets and prompts for user interaction.

Uploaded by

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

#C

The document contains a series of practical exercises involving matrix operations in Python, including accepting matrices from user input, displaying transposes, finding determinants, and performing arithmetic operations like addition and multiplication. It also checks for the existence of inverses for 2x2 and 3x3 matrices based on their determinants. Each exercise is structured with code snippets and prompts for user interaction.

Uploaded by

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

PRACTICAL : 1

Q1
# Accept R * C matric from the user

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(0, rows):
print(f"Entered row {i}")
matrix.append([])
for j in range(0, columns):
element = int(input("Enter an element: "))
matrix[i].append(element)

for i in range(0, rows):


for j in range(0, columns):
print(matrix[i][j], end = " ")
print()

Q2
# Accept R * C matric from the user & display its transpose

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(0, rows):
print(f"Entered row {i}")
matrix.append([])
for j in range(0, columns):
element = int(input("Enter an element: "))
matrix[i].append(element)

print("Matrix:")
for i in range(0, rows):
for j in range(0, columns):
print(matrix[i][j], end = " ")
print()

print("Transpose matrix: ")


for i in range(0, rows):
for j in range(0, columns):
print(matrix[j][i], end = " ")
print()

Q3
# Display second column

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(rows):
print(f"Entered row {i + 1}")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

for i in range(rows):
for j in range(columns):
if j == 1:
print(matrix[i][j], end = " ")

Q4
# Display second row

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

for i in range(rows):
print(f"Entered row {i + 1}")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the elements at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

for i in range(rows):
if i == 1:
for j in range(columns):
print(matrix[i][j], end = " ")

Q5
# Display the last row

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

for i in range(rows):
print(f"Entered the row {i + 1}:")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

for i in range(rows):
if i == rows - 1:
for j in range(columns):
print(matrix[i][j], end = " ")

Q6
# Display specified row/column

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

for i in range(rows):
print(f"Entered row {i + 1}:")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)
print()

print("Enter '1' if you want to display row")


print("Enter '2' if you want to display column")
choice = input("Enter the choice (1/2): ")
if choice == '1':
specified_row = int(input("Enter which row you want to display: "))
for i in range(rows):
if i == specified_row - 1:
for j in range(columns):
print(matrix[i][j], end = " ")

elif choice == '2':


specified_column = int(input("Enter which column you want to display: "))
for i in range(rows):
for j in range(columns):
if j == specified_column - 1:
print(matrix[i][j], end = " ")

else:
print("Invalid choice, choose between 1 and 2.")

Q7
# Accept RxC matrix and take a user input scalar value and multiply it with the
matrix

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

for i in range(rows):
print(f"Entered row {i + 1}:")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

scalar_value = int(input("Enter a scalar value: "))


for i in range(rows):
for j in range(columns):
print(matrix[i][j] * scalar_value, end = " ")
print()

Q8
# Accept two matrices and add them

matrix_1 = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(0, rows):
print(f"Entered row {i + 1}")
matrix_1.append([])
for j in range(0, columns):
element = int(input("Enter the element: "))
matrix_1[i].append(element)
for i in range(0, rows):
for j in range(0, columns):
print(matrix_1[i][j], end = " ")
print()
print()

matrix_2 = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(0, rows):
print(f"Entered row {i + 1}")
matrix_2.append([])
for j in range(0, columns):
element = int(input("Enter the element: "))
matrix_2[i].append(element)
for i in range(0, rows):
for j in range(0, columns):
print(matrix_2[i][j], end = " ")
print()
print()

print("Sum of matrices:")
for i in range(0, rows):
for j in range(0, columns):
print(matrix_1[i][j] + matrix_2[i][j], end = " ")
print()

Q9
# Accept two matrices and find 2A + B

print("Matrix A")
A = []
rows_1 = int(input("Enter the number of columns: "))
columns_1 = int(input("Enter the number of columns: "))

for i in range(rows_1):
print(f"Entered row {i + 1}:")
A.append([])
for j in range(columns_1):
elements_1 = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
A[i].append(elements_1)

for i in range(rows_1):
for j in range(columns_1):
print(A[i][j], end = " ")
print()

print("Matrix B")
B = []
rows_2 = int(input("Enter the number of columns: "))
columns_2 = int(input("Enter the number of columns: "))

for i in range(rows_2):
print(f"Entered row {i + 1}:")
B.append([])
for j in range(columns_2):
elements_2 = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
B[i].append(elements_2)

for i in range(rows_2):
for j in range(columns_2):
print(B[i][j], end = " ")
print()

print("2A + B:")
for i in range(rows_1):
for j in range(columns_1):
print(2 * A[i][j] + B[i][j], end = " ")
print()

Q10

# Accept two matrices A & B. Check if they are well defined. If yes, then find AB.

print("Matrix A:")
A = []
rows_1 = int(input("Enter the number of rows: "))
columns_1 = int(input("Enter the number of columns: "))
for i in range(rows_1):
print(f"Entered row {i + 1}:")
A.append([])
for j in range(columns_1):
elements_1 = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
A[i].append(elements_1)
print("Matrix A:")
for i in range(rows_1):
for j in range(columns_1):
print(A[i][j], end = " ")
print()

print("Matrix B:")
B = []
rows_2 = int(input("Enter the number of rows: "))
columns_2 = int(input("Enter the number of columns: "))
for i in range(rows_2):
print(f"Entered row {i + 1}:")
B.append([])
for j in range(columns_2):
elements_2 = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
B[i].append(elements_2)
print("Matrix B:")
for i in range(rows_2):
for j in range(columns_2):
print(B[i][j], end = " ")
print()

if columns_2 == rows_1:
print("The matrix is well defined.")
print("A * B:")
for i in range(rows_1):
for j in range(columns_2):
print(A[i][0] * B[0][j] + A[i][1] * B[1][j], end = " ")
print()
else:
print("The matrices are not well defined. Hence, their product cannot be
found.")

Q11

# Accept 3x3 matrices A, B, C & find A + B + C

print("Matrix A:")
A = []
rows_1 = int(input("Enter the number of rows: "))
columns_1 = int(input("Enter the number of columns: "))
for i in range(rows_1):
print(f"Entered row {i + 1}:")
A.append([])
for j in range(columns_1):
elements_1 = int(input(f"Enter the elements at position {[i + 1], [j + 1]}:
"))
A[i].append(elements_1)
print("Matrix A:")
for i in range(rows_1):
for j in range(columns_1):
print(A[i][j], end = " ")
print()

print("Matrix B:")
B = []
rows_2 = int(input("Enter the number of rows: "))
columns_2 = int(input("Enter the number of columns: "))
for i in range(rows_2):
print(f"Entered row {i + 1}:")
B.append([])
for j in range(columns_2):
elements_2 = int(input(f"Enter the elements at position {[i + 1], [j + 1]}:
"))
B[i].append(elements_2)
print("Matrix B:")
for i in range(rows_2):
for j in range(columns_2):
print(B[i][j], end = " ")
print()

print("Matrix C:")
C = []
rows_3 = int(input("Enter the number of rows: "))
columns_3 = int(input("Enter the number of columns: "))
for i in range(rows_3):
print(f"Entered row {i + 1}:")
C.append([])
for j in range(columns_3):
elements_3 = int(input(f"Enter the elements at position {[i + 1], [j + 1]}:
"))
C[i].append(elements_3)
print("Matrix C:")
for i in range(rows_3):
for j in range(columns_3):
print(C[i][j], end = " ")
print()

print("A + B + C:")
for i in range(rows_1):
for j in range(columns_1):
print(A[i][j] + B[i][j] + C[i][j], end = " ")
print()

PRACTICAL : 2

Q1
# Accept a 2x2 matrix from yhe user and find its determinant

import numpy as np

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


determinant = np.linalg.det(matrix)
print(matrix)
print(f"Determinant: {determinant}")

Q2
# Accept 3x3 matrix & find its determinant

import numpy as np

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


determinant = np.linalg.det(matrix)
print(matrix)
print(f"Determinant: {determinant}")

Q3
# Accept RxC matrix and its determinant

import numpy as np

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(rows):
print(f"Entered row {i + 1}:")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)
print("Matrix:")
for i in range(rows):
for j in range(columns):
print(matrix[i][j], end = " ")
print()

array_matrix = np.array(matrix)
determinant = np.linalg.det(array_matrix)
print(f"Determinant: {determinant}")

Q4
# Accept two 2x2 matrices A & B from the user and find the determinant of matrix A
+ 2B

import numpy as np

print("Enter elements for matrix A:")


A = np.array([[int(input("a11: ")), int(input("a12: "))],
[int(input("a21: ")), int(input("a22: "))]])
print(A)
print()

print("Enter elements for matrix B:")


B = np.array([[int(input("b11: ")), int(input("b12: "))],
[int(input("b21: ")), int(input("b22: "))]])
print(B)
print()

a_2b = A + (2 * B)
print("A + 2B:")
print(a_2b)
determinant = np.linalg.det(a_2b)
print(f"Determinant: {determinant}")

Q5
# Accept three 2x2 matrices A, B, C from the user and find the determinant of
matrix A + B + C

import numpy as np

print("Enter elements for matrix A:")


A = np.array([[int(input("a11: ")), int(input("a12: "))],
[int(input("a21: ")), int(input("a22: "))]])
print(A)
print()

print("Enter elements for matrix B:")


B = np.array([[int(input("b11: ")), int(input("b12: "))],
[int(input("b21: ")), int(input("b22: "))]])
print(B)
print()

print("Enter elements for matrix C:")


C = np.array([[int(input("c11: ")), int(input("c12: "))],
[int(input("c21: ")), int(input("c22: "))]])
print(C)
print()

a_b_c = A + B + C
print("A + B + C:")
print(a_b_c)
determinant = np.linalg.det(a_b_c)
print(f"Determinant of A + B + C: {determinant}")

Q6
# Accept 2x2 matrix and check if its inverse exists

import numpy as np

print("Enter elements for the matrix:")


matrix = np.array([[int(input("m11: ")), int(input("m12: "))],
[int(input("m21: ")), int(input("m22: "))]])
print("Matrix:")
print(matrix)
print()

determinant = np.linalg.det(matrix)
print(f"Determinant of the matrix: {determinant}")

if determinant == 0:
print("Inverse doesn't exist for the above matrix.")
else:
print("Inverse exists for the above matrix.")

Q7
# Accept 3x3 matrix and check if its inverse exists

import numpy as np

print("Enter elements for the matrix:")


matrix = np.array([[int(input("m11: ")), int(input("m12: ")), int(input("m13: "))],
[int(input("m21: ")), int(input("m22: ")), int(input("m23: "))],
[int(input("m31: ")), int(input("m32: ")), int(input("m33:
"))]])
print("Matrix:")
print(matrix)
print()

determinant = np.linalg.det(matrix)
print(f"Determinant of the matrix: {determinant}")

if determinant == 0:
print("Inverse doesn't exist for the above matrix.")
else:
print("Inverse exists for the above matrix.")

Q8
# Accept RxC matrix and check if its inverse exists

import numpy as np

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(rows):
print(f"Entered row {i + 1}")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the elements at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

print("Matrix:")
for i in range(rows):
for j in range(columns):
print(matrix[i][j], end = " ")
print()

array_matrix = np.array(matrix)
determinant = np.linalg.det(array_matrix)
print(f"Determinant of the above matrix: {determinant}")

if determinant == 0:
print("Determinant doesn't exist for the above matrix.")
else:
print("Determinant exists for the above matrix.")

Q9
# Accept a 2x2 matrix and find its inverse

import numpy as np

print("Enter the elements for the matrix:")


matrix = np.array([[int(input("m11: ")), int(input("m12: "))],
[int(input("m21: ")), int(input("m22: "))]])
print("Matrix:")
print(matrix)
print()

determinant = np.linalg.det(matrix)
print(f"Determinant of the above matrix: {determinant}")
if determinant == 0:
print("Inverse doesn't exist for the above matrix.")
else:
print("Inverse exists for the above matrix.")
inverse_matrix = np.linalg.inv(matrix)
print("Inverse of the matrix:")
print(inverse_matrix)

Q10
# Accept a 3x3 matrix and find its inverse

import numpy as np

print("Enter the elements for the matrix:")


matrix = np.array([[int(input("m11: ")), int(input("m12: ")), int(input("m13: "))],
[int(input("m21: ")), int(input("m22: ")), int(input("m23: "))],
[int(input("m31: ")), int(input("m32: ")), int(input("m33:
"))]])
print("Matrix:")
print(matrix)
print()

determinant = np.linalg.det(matrix)
print(f"Determinant of the above matrix: {determinant}")
if determinant == 0:
print("Inverse doesn't exist for the above matrix.")
else:
print("Inverse exists for the above matrix.")
inverse_matrix = np.linalg.inv(matrix)
print("Inverse of the matrix:")
print(inverse_matrix)

Q11
# Accept a RxC matrix and find its inverse

import numpy as np

matrix = []
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(rows):
print(f"Entered row {i + 1}")
matrix.append([])
for j in range(columns):
elements = int(input(f"Enter the element at position {[i + 1], [j + 1]}:
"))
matrix[i].append(elements)

array_matrix = np.array(matrix)
print("Matrix:")
print(array_matrix)
determinant = np.linalg.det(array_matrix)
if determinant == 0:
print("Inverse doesn't exist for the above matrix.")
else:
print("Inverse exists for the above matrix.")
inverse_matrix = np.linalg.inv(array_matrix)
print("Inverse of the matrix:")
print(inverse_matrix)

PRACTICAL : 3

Q1
# Accept two vectors from the user and add them

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

def add(vector_1, vector_2):


return [element_1 + element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True)]

u = input_vector()
v = input_vector()

print(f"Vector u: {u}")
print(f"Vector v: {v}")
print(f"u + v = {add(u, v)}")

Q2
# Accept three vectors and add them

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]
def add(vector_1, vector_2, vector_3):
return [element_1 + element_2 + element_3 for element_1, element_2, element_3
in zip(vector_1, vector_2, vector_3, strict = True)]

x = input_vector()
y = input_vector()
z = input_vector()

print(f"Vector x: {x}")
print(f"Vector y: {y}")
print(f"Vector z: {z}")
print(f"x + y + z = {add(x, y, z)}")

Q3
# Accept 2 vectors and subtract them

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}:")) for i in range(dimension)]

def subtract(vector_1, vector_2):


return [element_1 - element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True)]

u = input_vector()
v = input_vector()
print(f"u - v = {subtract(u, v)}")

Q4
# Accept a vector and scalar and multiply them(s * x)

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]
s = input_vector()
print(f"s = {s}")

scalar_value = int(input("Enter a scalar value to multiply with the vector: "))


print(f"Scalar value: {scalar_value}")
x = scalar_value
print(f"x = {x}")

def scalar_multiply(vector, scalar):


return [scalar * element for element in vector]

print(f"s * x = {scalar_multiply(s, x)}")

Q5
# Accept three vectors and multiply their sum by 3

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

x = input_vector()
y = input_vector()
z = input_vector()
print(f"x = {x}")
print(f"y = {y}")
print(f"z = {z}")

def add(vector_1, vector_2, vector_3):


return [element_1 + element_2 + element_3
for element_1, element_2, element_3
in zip(vector_1, vector_2, vector_3, strict = True)]

sum_vectors = add(x, y, z)
print(f"x + y + z = {sum_vectors}")

scalar_value = int(input("Enter a scalar value to multiply with the sum of vectors:


"))
print(f"Scalar value(s): {scalar_value}")
def scalar_multiply(scalar, sum_of_vectors):
return [scalar * element for element in sum_of_vectors]

print(f"s * (x + y + z) = {scalar_multiply(scalar_value, sum_vectors)}")

Q6
# Accept two vectors and find (2 * x) + (3 * y) / (2x + 3y)

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

x = input_vector()
y = input_vector()
print(f"x = {x}")
print(f"y = {y}")

result = [(2 * x) + (3 * y) for x, y in zip(x, y)]


print(f"2x + 3y = {result}")

Q7
# Accept three vectors and find 2x - 3y +z

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

x = input_vector()
y = input_vector()
z = input_vector()
print(f"x = {x}")
print(f"y = {y}")
print(f"z = {z}")

result = [(2 * x) - (3 * y) + z for x, y, z in zip(x, y, z)]


print(f"2x - 3y + z = {result}")

Q8
# Accept two vectors and find 2x - 3y
def input_vector(dtype = float):
dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

x = input_vector()
y = input_vector()
print(f"x = {x}")
print(f"y = {y}")

result = [(2 * x) - (3 * y) for x, y in zip(x, y)]


print(f"2x - 3y = {result}")

Q9
# Accept two vectors & find their dot product

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def dot_product(vector_1, vector_2):


return sum(vector_1[i] * vector_2[i] for i in range(len(vector_1)))

print(f"Dot product of <u, v> = {dot_product(u, v)}")

Q10
# Accept two vectors and find the dot product of 2x, 3y

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

x = input_vector()
y = input_vector()
print(f"x = {x}")
print(f"y = {y}")

product_1 = [(2 * x) for x in x]


print(f"2x = {product_1}")
product_2 = [(3 * y) for y in y]
print(f"3y = {product_2}")

def dot_product(vector_1, vector_2):


return sum(product_1[i] * product_2[i] for i in range(len(vector_1)))
print(f"Dot product <2x, 3y> = {dot_product(product_1, product_2)}")

Q11
# Accept two vectors from the user & perform a menu driven operation on them(Add,
Subtract, Dot product)

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def main():
while True:
print("Vector operations menu:")
print("1. Add")
print("2. Subtract")
print("3. Dot product")
print("4. Exit")

choice = input("Enter your choice between (1 - 4): ")


if choice == '1':
def add_vectors(vector_1, vector_2):
return [element_1 + element_2 for element_1, element_2 in
zip(vector_1, vector_2)]
result = add_vectors(u, v)
print(f"u + v = {result}")
elif choice == '2':
def subtract_vectors(vector_1, vector_2):
return [element_1 - element_2 for element_1, element_2 in
zip(vector_1, vector_2)]
result = subtract_vectors(u, v)
print(f"u - v = {result}")
elif choice == '3':
def dot_product(vector_1, vector_2):
return sum(vector_1[i] * vector_2[i] for i in range(len(vector_1)))
result = dot_product(u, v)
print(f"<u, v> = {result}")
elif choice == '4':
print("Exiting program..")
break
else:
print("Your choice is invalid, choose between (1 - 4).")

if __name__ == "__main__":
main()

Q12
# Accept two vectors and generate a linear combination

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def linear_combination(vector_1, vector_2, c1, c2):


return [c1 * element_1 + c2 * element_2
for element_1, element_2 in zip(vector_1, vector_2, strict = True)]
if len(u) == len(v):
coefficient_1 = int(input("Enter a scalar coefficient(c1): "))
coefficient_2 = int(input("Enter another scalar coefficient(c2): "))
result = linear_combination(u,v, coefficient_1, coefficient_2)
print(f"Linear combination ({coefficient_1} * u + {coefficient_2} * v):
{result}")
else:
print("The vectors aren't of same dimensions."
"hence, their linear combination connot be found.")

PRACTICAL : 4

Q1
#Accept 2*2 matrix and convert it into Row Echelon form
import numpy as np
from math import isclose

def input_mat(square=False, dtype=float):


if square:
r=c = int(input("Enter the dimension of square matrix : "))
else:
r = int(input("Enter the number of row : "))
c = int(input("Enter the number of column : "))

ret_mat = []
for i in range(r):
ret_row = [dtype(input(f"Enter element for position [{i+1},{j+1}]"))
for j in range(c)]
ret_mat.append(ret_row)
return ret_mat
def echelon_form(mat, pivots = False):
mat = np.array(mat, dtype=float)
r,c = mat.shape
pivot_set = set()
shift = 0

for i in range(min(r,c)):
while i+shift < c and all(isclose(elem,0,abs_tol=1e-08)
for elem in mat[i:,i+shift]):
shift += 1
if i+shift == c:
break
pivots = mat[i, i+shift]
for next_row in range(i+1, r):
below_pivot = mat[next_row, i+shift]
if not isclose(below_pivot, 0, abs_tol=1e-08):
#if not isclose(below_pivot, 0, abs_tol=1e-08):
mat[next_row] -= (below_pivot/pivots)*mat[i]
else:
mat[[i, next_row]] = mat[[next_row, i]]
pivots = below_pivot
pivot_set.add(i+shift)
mat[i, :i+shift] = 0
if pivots:
return mat, pivot_set
return mat
A = input_mat()
print("Matrix A : ", A)
print("Echelon form A: \n ",echelon_form(A))
print("Echelon form A , with pivot cloumn : \n", echelon_form(A, pivots=True))

Q2
#Find the Rank of r*c matrix
import numpy as np
from math import isclose

def input_mat(square=False, dtype=float):


if square:
r=c = int(input("Enter the dimension of square matrix : "))
else:
r = int(input("Enter the number of row : "))
c = int(input("Enter the number of column : "))

ret_mat = []
for i in range(r):
ret_row = [dtype(input(f"Enter element for position [{i+1},{j+1}]"))
for j in range(c)]
ret_mat.append(ret_row)
return ret_mat
def echelon_form(mat, pivots = False):
mat = np.array(mat, dtype=float)
r,c = mat.shape
pivot_set = set()
shift = 0

for i in range(min(r,c)):
while i+shift < c and all(isclose(elem,0,abs_tol=1e-08)
for elem in mat[i:,i+shift]):
shift += 1
if i+shift == c:
break
pivots = mat[i, i+shift]
for next_row in range(i+1, r):
below_pivot = mat[next_row, i+shift]
if not isclose(below_pivot, 0, abs_tol=1e-08):
if not isclose(below_pivot, 0, abs_tol=1e-08):
mat[next_row] -= (below_pivot/pivots)*mat[i]
else:
mat[[i, next_row]] = mat[[next_row, i]]
pivots = below_pivot
pivot_set.add(i+shift)
mat[i, :i+shift] = 0
if pivots:
return mat, pivot_set
return mat
def rank(mat):
mat, pivots = echelon_form(mat, pivots=True)
return len(pivots)
A = input_mat()
print("Matrix A : ", A)
print("Echelon form A: \n ",echelon_form(A))
print("Echelon form A , with pivot cloumn : \n", echelon_form(A, pivots=True))

Q---
import numpy as np
from math import isclose
def input_mat(square=False, dtype=float):
if square:
r=c=int(input("Enter the dimension of the square matrix:"))
else:
r=int(input("Enter the no of rows:"))
c=int(input("Enter no of columns:"))

ret_mat = []

'''def row_echelon_form(matrix):
# Convert the input matrix to a NumPy array
A = np.array(matrix, dtype=float)
rows, cols = A.shape

for r in range(rows):
# Find the pivot for the current row
pivot = A[r, r]

# If the pivot is zero, we need to swap with a lower row


if pivot == 0:
for i in range(r + 1, rows):
if A[i, r] != 0:
A[[r, i]] = A[[i, r]] # Swap rows
pivot = A[r, r]
break

# If the pivot is still zero, continue to the next row


if pivot == 0:
continue

# Normalize the pivot row


A[r] = A[r] / pivot

# Eliminate the entries below the pivot


for i in range(r + 1, rows):
A[i] = A[i] - A[i, r] * A[r]

return A'''

ref_matrix = row_echelon_form(matrix)
print("Row Echelon Form:")
print(ref_matrix)

PRACTICAL : 5

Q1
# Accept two vectors form the user and find their inner product

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
vector = []
for i in range(dimension):
element = dtype(input(f"Enter an element at position {i + 1}: "))
vector.append(element)
return vector

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))
u = input_vector()
v = input_vector()

print(f"Vector u: {u}")
print(f"Vector v: {v}")
print(f"<u, v> = {inner_product(u, v)}")

Q2
# Accept two vectors from the user and check if they are orthogonal

from math import isclose

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"enter element {i + 1}: ")) for i in range(dimension)]
u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))
print(f"<u, v> = {inner_product(u, v)}")

def is_orthogonal(vector_1, vector_2):


return isclose(inner_product(vector_1, vector_2), 0, abs_tol = 1e-8)
print(f"Are u & v orthogonal> : {is_orthogonal(u, v)}")

Q3
# Accept a vector from the user and find its norm

from math import sqrt

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]
u = input_vector()
print(f"u = {u}")

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))
print(f"<u, u> = {inner_product(u, u)}")

def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")
Q4
# Accept a vector and normalize it

from math import sqrt


def input_vector(dtype = float):
dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]
u = input_vector()
print(f"u = {u}")

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))
print(f"<u, u> = {inner_product(u, u)}")

def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")

def scale(scalar, vector):


return [scalar * element for element in vector]

def normalize(vector):
return scale(1 / norm(vector), vector)
print(f"u / ||u|| = {normalize(u)}")

Q5
# Accept two vectors & check if they are orthormal

from math import isclose, sqrt

def input_vector(dtype=float):
dimension = int(input("Enter the dimension of vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2))

print(f"<u, u> = {inner_product(u, u)}")


print(f"<v, v> = {inner_product(v, v)}")

def is_orthogonal(vector_1, vector_2):


return isclose(inner_product(vector_1, vector_2), 0, abs_tol=1e-8)

print(f"Is u orthogonal to v? {is_orthogonal(u, v)}")

def norm(vector):
return sqrt(inner_product(vector, vector))

print(f"||u|| = {norm(u)}")
print(f"||v|| = {norm(v)}")
def is_orthonormal(vector_1, vector_2):
return is_orthogonal(vector_1, vector_2) and isclose(norm(vector_1), 1,
abs_tol=1e-8) and isclose(norm(vector_2), 1, abs_tol=1e-8)

print(f"Are u and v orthonormal? {is_orthonormal(u, v)}")

Q6
# Accept two vectors and find the angle between them

from math import sqrt, acos, degrees

def input_vector(dtype =float):


dimension = int(input("Enter the dimension: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]
u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")

def inner_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))
print(f"<u, v> = {inner_product(u, v)}")

def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")
print(f"||v|| = {norm(v)}")

def angle(vector_1, vector_2):


theta_radians = acos(inner_product(vector_1, vector_2) / (norm(vector_1) *
norm(vector_2)))
return degrees(theta_radians)
print(f"Angle between the vectors: {angle(u, v)}")

Q7
# Accept a set of vectors & check if they are orthogonal

from math import isclose, sqrt

def input_vector(dtype=float):
dimension = int(input("Enter the dimension of the vector: "))
return [dtype(input(f"Enter element {i + 1}: ")) for i in range(dimension)]

def input_vector_set():
num_vectors = int(input("Enter the number of vectors: "))
vectors = [input_vector() for _ in range(num_vectors)]
return vectors

def dot_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2))

def is_orthogonal_set(vectors):
num_vectors = len(vectors)
for i in range(num_vectors):
for j in range(i + 1, num_vectors):
if not isclose(dot_product(vectors[i], vectors[j]), 0, abs_tol=1e-8):
return False
return True

vector_set = input_vector_set()

for i, vector in enumerate(vector_set):


print(f"Vector {i + 1}: {vector}")

print(f"Is the set orthogonal? {is_orthogonal_set(vector_set)}")

PRACTICAL : 6

Q1
# Implement Gram Schmidt Orthogonalization on a set of vectors to construct an
orthogonal set

from math import sqrt

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
vector = []
for i in range(dimension):
element = dtype(input(f"Enter element {i + 1}:"))
vector.append(element)
return vector

def scale(scalar, vector):


return [scalar * element for element in vector]

def subtract(vector_1, vector_2):


return [element_1 - element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True)]

def dot_product(vector_1, vector_2):


return sum(element_1* element_2 for element_1, element_2 in zip(vector_1,
vector_2, strict = True))

def norm(vector):
return (dot_product(vector, vector))

def gram_schmidt(* vectors):


orthogonal_set = []
for vector in vectors:
result = vector
for orthogonal_vector in orthogonal_set:
proj = scale(dot_product(vector, orthogonal_vector) /
dot_product(orthogonal_vector, orthogonal_vector), orthogonal_vector)
result = subtract(result, proj)
orthogonal_set.append([round(element, 8) for element in result])
return orthogonal_set

u = input_vector()
v = input_vector()
w = input_vector()
print(f"Set (u, v, w): {u, v, w}")
print(f"Orthogonalized set from set (u, v, w): {gram_schmidt(u, v, w)}")

Q2
# Implement Gram Schmidt Orthogonalization on a set of vectors to construct an
orthognormal set

from math import sqrt

def input_vector(dtype = float):


dimension = int(input("Enter the dimension of the vector: "))
vector = []
for i in range(dimension):
element = dtype(input(f"Enter element {i + 1}:"))
vector.append(element)
return vector

def scale(scalar, vector):


return [scalar * element for element in vector]

def subtract(vector_1, vector_2):


return [element_1 - element_2 for element_1, element_2 in zip(vector_1,
vector_2)]

def dot_product(vector_1, vector_2):


return sum(element_1 * element_2 for element_1, element_2 in zip(vector_1,
vector_2))

def norm(vector):
return sqrt(dot_product(vector, vector))

def gram_schmidt(* vectors):


orthonormal_set = []
for vector in vectors:
result = vector
for orthogonal_vector in orthonormal_set:
proj = scale(dot_product(vector, orthogonal_vector) /
dot_product(orthogonal_vector, orthogonal_vector), orthogonal_vector)
result = subtract(result, proj)
result_norm = norm(result)
if result_norm != 0:
result = scale(1 / result_norm, result)
orthonormal_set.append([round(element, 8) for element in result])
return orthonormal_set

u = input_vector()
v = input_vector()
w = input_vector()

print(f"Set (u, v, w): {u, v, w}")


print(f"Orthonormalized set from set (u, v, w): {gram_schmidt(u, v, w)}")
PRACTICAL : 7

Q1
# Find characteristic equation of a matrix

from sympy import Symbol, eye, det, Matrix, S

def input_matrix(square = False, dtype = float):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position [{i + 1}, {j +
1}]: "))
for j in range (columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

A = Matrix(input_matrix(square = True, dtype = S))


print(f"Matrix A: {A}")
print(f"Characteristic polynomial of A: {characteristic_polynomial(A)}")

Q2
#Find minimal polynomial of matrix(user input)
from sympy import Symbol, eye, det, Matrix, S
import sympy as sp

def input_mat(square=False, dtype=float): #for user input


if square:
r=c=int(input("Enter the dimension of square matrix:"))
else:
r=int(input("Enter the no.of rows:"))
c=int(input("Enter the no.of cols:"))

ret_mat=[]
for i in range(r):
ret_row=[dtype(input(f"Enter elements for position [{i+1},{j+1}]:"))for j
in range(c)]
ret_mat.append(ret_row)
return ret_mat
x = sp.symbols('x')
matrix_data = input_mat()
#matrix_data=Matrix([[1,2],[3,4]]) #For predefined matrix

if matrix_data:
A = sp.Matrix(matrix_data)
n = A.shape[0]
I = sp.eye(n)

charpoly_expr = A.charpoly(x).as_expr()
print("Characteristic Polynomial:", charpoly_expr)

eigs = A.eigenvals()
print("Eigenvalues:", eigs)

# Cayley–Hamilton approach to find the Minimal Polynomial


min_poly = 1
for r, alg_mult in eigs.items():
d = 1
while True:
M = (A - r * I) ** d
nullity = len(M.nullspace())
if nullity == alg_mult:
break
d += 1
min_poly *= (x - r) ** d

print("Minimal Polynomial (Cayley-Hamilton):", min_poly)


print("Expanded Minimal Polynomial:", sp.expand(min_poly))

PRACTICAL : 8

Q1
# Find all the eigenvalues of a matrix

from sympy import Symbol, eye, det, Matrix, S, roots

def input_matrix(square = False, dtype = float):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position [{i + 1}, {j +
1}]: "))
for j in range (columns)]
retrieve_matrix.append(input_row)
return retrieve_matrix

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)

A = Matrix(input_matrix(square = True, dtype = S))


print(f"Matrix A: {A}")
print(f"Eigenvalues of the matrix: {eigen_values(A)}")

Q2
# Accept two 2x2 matrices, find all the eigenvalues of the matrix A + 2B

from sympy import Symbol, eye, det, Matrix, S, roots

def input_matrix(dtype = float):


rows = columns = 2
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix, variable =
"lambda")
return roots(characteristic_equation)

print("Enter elements for matrix A:")


A = input_matrix(dtype = S)
print("Enter elements for matrix B:")
B = input_matrix(dtype = S)
A_2B = A + 2 * B
print(f"Matrix A: {A}")
print(f"Matrix B: {B}")
print(f"Matrix A + 2B = {A_2B}")
print(f"Eigenvalues of matrix A + 2B = {eigen_values(A_2B)}")

Q3
# Find all the eigenvalues and find the corresponding eigenvectors of a matrix

from sympy import Symbol, roots, det, Matrix, eye

def input_matrix(square = False, dtype = int):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)

def eigen_vectors(matrix):
A_LI = get_A_LI(matrix)
characteristic_equation = det(A_LI)
eigenvalues = roots(characteristic_equation)
eigenvectors = [A_LI.subs("lambda", eigenvalue).nullspace() for eigenvalue in
eigenvalues]
return eigenvalues, eigenvectors

A = Matrix(input_matrix(square = True, dtype = int))


print(f"Matrix A: {A}")
print(f"Eigenvalues with their algebraic multiplicity: {eigen_values(A)}")
print(f"Eigenvector of A with algebraic and geometric multiplicities:
{eigen_vectors(A)}")

Q4
# Find diagonal matrix of a matrix

from sympy import Symbol, roots, det, Matrix, eye

def input_matrix(square = False, dtype = int):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)

def eigen_vectors(matrix):
A_LI = get_A_LI(matrix)
characteristic_equation = det(A_LI)
eigenvalues = roots(characteristic_equation)
eigenvectors = [A_LI.subs("lambda", eigenvalue).nullspace() for eigenvalue in
eigenvalues]
return eigenvalues, eigenvectors

def diagonal_matrix(matrix):
try:
modal, diagonal = matrix.diagonalize()
return diagonal
except:
return "The matrix is not diagonalizable."

A = Matrix(input_matrix(square = True, dtype = int))


print(f"Matrix A: {A}")
print(f"Eigenvalues with their algebraic multiplicity: {eigen_values(A)}")
print(f"Eigenvector of A with algebraic and geometric multiplicities:
{eigen_vectors(A)}")
print(f"Diagonal matrix of A: {diagonal_matrix(A)}")

Q5
# Find modal matrix of a matrix

from sympy import Symbol, roots, det, Matrix, eye

def input_matrix(square = False, dtype = int):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)

def eigen_vectors(matrix):
A_LI = get_A_LI(matrix)
characteristic_equation = det(A_LI)
eigenvalues = roots(characteristic_equation)
eigenvectors = [A_LI.subs("lambda", eigenvalue).nullspace() for eigenvalue in
eigenvalues]
return eigenvalues, eigenvectors

def modal_matrix(matrix):
try:
P, D = matrix.diagonalize()
return P
except:
return "The matrix is not diagonalizable."

A = Matrix(input_matrix(square = True, dtype = int))


print(f"Matrix A: {A}")
print(f"Eigenvalues with their algebraic multiplicity: {eigen_values(A)}")
print(f"Eigenvector of A with algebraic and geometric multiplicities:
{eigen_vectors(A)}")
print(f"Modal matrix of A: {modal_matrix(A)}")

Q6
# Find diagonal & modal matrix of a matrix

from sympy import Symbol, roots, det, Matrix, eye

def input_matrix(square = False, dtype = int):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return Matrix(retrieve_matrix)

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristic_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)

def eigen_vectors(matrix):
A_LI = get_A_LI(matrix)
characteristic_equation = det(A_LI)
eigenvalues = roots(characteristic_equation)
eigenvectors = [A_LI.subs("lambda", eigenvalue).nullspace() for eigenvalue in
eigenvalues]
return eigenvalues, eigenvectors

def diagonal_matrix(matrix):
try:
P, D = matrix.diagonalize()
return D
except:
return "The matrix is not diagonalizable."

def modal_matrix(matrix):
try:
P, D = matrix.diagonalize()
return P
except:
return "The matrix is not diagonalizable."

A = Matrix(input_matrix(square = True, dtype = int))


print(f"Matrix A: {A}")
print(f"Eigenvalues with their algebraic multiplicity: {eigen_values(A)}")
print(f"Eigenvector of A with algebraic and geometric multiplicities:
{eigen_vectors(A)}")
print(f"Diagonal matrix of A: {diagonal_matrix(A)}")
print(f"Modal matrix of A: {modal_matrix(A)}")

PRACTICAL : 9

Q1
#Accept square matrix from user and check if it's derogatory or not
from sympy import Symbol, eye, det, Matrix, S, roots

def input_mat(square=False, dtype=float): #for user input


if square:
r=c=int(input("Enter the dimension of square matrix:"))
else:
r=int(input("Enter the no.of rows:"))
c=int(input("Enter the no.of cols:"))

ret_mat=[]
for i in range(r):
ret_row=[dtype(input(f"Enter elements for position [{i+1},{j+1}]:"))for j
in range(c)]
ret_mat.append(ret_row)
return ret_mat

def get_A_LI(mat,var='lambda'):
r,c=mat.shape
L=Symbol(var)
I=eye(r)

return mat - L*I

def charac_poly(mat,var='lambda'):
A_LI = get_A_LI(mat,var=var)

return det(A_LI).as_poly().monic()

def eig_vals(mat):
charac = charac_poly(mat)
return roots(charac)

def eig_vec(mat):
A_LI = get_A_LI(mat)
charac = det(A_LI)
vals = roots(charac)
vecs = [A_LI.subs('lambda',val).nullspace() for val in vals]
return vals, vecs

def is_derogatory(mat):
vals, vecs = eig_vec(mat)
for val,eigenvec_list in zip(vals.keys(),vecs):
alg_mult = vals[val]
geo_mult = len(eigenvec_list)
if alg_mult > geo_mult:
return True
return False

A=Matrix(input_mat(square=True,dtype=S))
#A=Matrix([[1,0,2],[2,1,0],[0,0,4]])#for predefined matrix
print("Matrix A:",A)
print("Eigenvalues of a with their algebric multiplicity:",eig_vals(A))
print("Is the matrix derogatory?:",is_derogatory(A))

Q2
# Accept a square matrix & check if it's positive or negative
from sympy import Symbol, eye, det, Matrix, S, roots

def input_matrix(square = False, dtype = float):


if square:
rows = columns = int(input("Enter the dimension of the matrix: "))
else:
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
retrieve_matrix = []
for i in range(rows):
input_row = [dtype(input(f"Enter the element at position {[i + 1], [j +
1]}: ")) for j in range(columns)]
retrieve_matrix.append(input_row)
return retrieve_matrix

def get_A_LI(matrix, variable = "lambda"):


rows, columns = matrix.shape
L = Symbol(variable)
I = eye(rows)
return matrix - L * I

def characteristics_polynomial(matrix, variable = "lambda"):


A_LI = get_A_LI(matrix, variable = variable)
return det(A_LI).as_poly().monic()

def eigen_values(matrix):
characteristics_equation = characteristics_polynomial(matrix)
return roots(characteristics_equation)

def is_positive_definite(matrix):
if matrix != matrix.T:
return False
values = eigen_values(matrix)
return all(values > 0 for value in values)

def is_negative_definite(matrix):
if matrix != matrix.T:
return False
values = eigen_values(matrix)
return all(values < 0 for value in values)

A = Matrix(input_matrix(square = True, dtype = S))


print(f"Matrix A: {A}")
print(f"Eigen values of A with their algebraic multiplicity: {eigen_values(A)}")
print(f"Is A a positive definite: {is_positive_definite(A)}")
print(f"Is A a negative definite: {is_negative_definite(A)}")

PRACTICAL : 10

Q1.GAUSSAIN ELEM METHOD


import numpy as np
import sympy as sp

n = int(input("Enter the number of equations: "))


m = int(input("Enter the number of variables: "))

variables = sp.symbols(' '.join([f'x{i+1}' for i in range(m)]))

A = np.array([list(map(float, input(f"Enter coefficients of equation {i+1} (space


seperated): ").split())) for i in range(n)])

b = np.array(list(map(float, input("Enter the right hand constant terms (space


seperated): ").split())))

A_sym = sp.Matrix(A)
b_sym = sp.Matrix(b)

# Solve using SymPy (handles any case)


solution = sp.linsolve((A_sym, b_sym), *variables)

# Print the solution


print("\nSolution:")
if len(solution) == 0:
print("No solution exists.")
elif len(solution) == 1:
print("Unique solution:")
for sol in solution:
for var, val in zip(variables, sol):
print(f"{var} = {val}")
else:
print("Infinite solutions:")
print(solution)

Q2.CRAMERS RULE
import numpy as np
def cramer_rule(A,b):
n = len(b)
det_A = np.linalg.det(A)

if det_A == 0:
raise ValueError("This system has no unique solution(determinant is zero")

x = np.zeros(n)
for i in range(n):
A_i = A.copy()
A_i[:,i]=b
x[i] = np.linalg.det(A_i)/det_A
return x

A = np.array([[4,-3],[2,5]],dtype=float)
b = np.array([5,1],dtype=float)
solution = cramer_rule(A,b)
print("Solution :",solution)

Q3. BACK SUBST METHOD


import numpy as np
def back_substitution(U, b):
"""
Solves an upper triangular system Ux = b using back substitution.

Parameters:
U (numpy array): Upper triangular coefficient matrix
b (numpy array): Constant matrix

Returns:
list: Solution for the system of equations
"""
n = len(b)
x = np.zeros(n)

# Start from the last row and move upwards


for i in range(n - 1, -1, -1):
if U[i, i] == 0:
raise ValueError("Singular matrix detected, back substitution cannot
proceed.")

x[i] = (b[i] - np.dot(U[i, i + 1:], x[i + 1:])) / U[i, i]

return x

# Taking user input


n = int(input("Enter the number of equations/variables: "))

print(f"Enter the {n}x{n} upper triangular matrix:")


U = []
for i in range(n):
row = list(map(float, input(f"Row {i+1}: ").split()))
U.append(row)

print("Enter the constant matrix (values on the right-hand side):")


b = list(map(float, input().split()))

# Convert to numpy arrays


U = np.array(U, dtype=float)
b = np.array(b, dtype=float)

# Solve using Back Substitution


try:
solution = back_substitution(U, b)
print("Solution:", solution)
except ValueError as e:
print(e)

You might also like