#C
#C
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)
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()
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()
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)
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
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
Q2
# Accept 3x3 matrix & find its determinant
import numpy as np
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
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
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
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
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
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
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
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
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
u = input_vector()
v = input_vector()
print(f"u - v = {subtract(u, v)}")
Q4
# Accept a vector and scalar and multiply them(s * x)
Q5
# Accept three vectors and multiply their sum by 3
x = input_vector()
y = input_vector()
z = input_vector()
print(f"x = {x}")
print(f"y = {y}")
print(f"z = {z}")
sum_vectors = add(x, y, z)
print(f"x + y + z = {sum_vectors}")
Q6
# Accept two vectors and find (2 * x) + (3 * y) / (2x + 3y)
x = input_vector()
y = input_vector()
print(f"x = {x}")
print(f"y = {y}")
Q7
# Accept three vectors and find 2x - 3y +z
x = input_vector()
y = input_vector()
z = input_vector()
print(f"x = {x}")
print(f"y = {y}")
print(f"z = {z}")
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}")
Q9
# Accept two vectors & find their dot product
u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")
Q10
# Accept two vectors and find the dot product of 2x, 3y
x = input_vector()
y = input_vector()
print(f"x = {x}")
print(f"y = {y}")
Q11
# Accept two vectors from the user & perform a menu driven operation on them(Add,
Subtract, Dot product)
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")
if __name__ == "__main__":
main()
Q12
# Accept two vectors and generate a linear combination
u = input_vector()
v = input_vector()
print(f"u = {u}")
print(f"v = {v}")
PRACTICAL : 4
Q1
#Accept 2*2 matrix and convert it into Row Echelon form
import numpy as np
from math import isclose
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
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]
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
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
Q3
# Accept a vector from the user and find its norm
def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")
Q4
# Accept a vector and normalize it
def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")
def normalize(vector):
return scale(1 / norm(vector), vector)
print(f"u / ||u|| = {normalize(u)}")
Q5
# Accept two vectors & check if they are orthormal
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 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)
Q6
# Accept two vectors and find the angle between them
def norm(vector):
return sqrt(inner_product(vector, vector))
print(f"||u|| = {norm(u)}")
print(f"||v|| = {norm(v)}")
Q7
# Accept a set of vectors & check if they are orthogonal
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 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()
PRACTICAL : 6
Q1
# Implement Gram Schmidt Orthogonalization on a set of vectors to construct an
orthogonal set
def norm(vector):
return (dot_product(vector, vector))
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
def norm(vector):
return sqrt(dot_product(vector, vector))
u = input_vector()
v = input_vector()
w = input_vector()
Q1
# Find characteristic equation of a matrix
Q2
#Find minimal polynomial of matrix(user input)
from sympy import Symbol, eye, det, Matrix, S
import sympy as sp
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)
PRACTICAL : 8
Q1
# Find all the eigenvalues of a matrix
def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix)
return roots(characteristic_equation)
Q2
# Accept two 2x2 matrices, find all the eigenvalues of the matrix A + 2B
def eigen_values(matrix):
characteristic_equation = characteristic_polynomial(matrix, variable =
"lambda")
return roots(characteristic_equation)
Q3
# Find all the eigenvalues and find the corresponding eigenvectors of a matrix
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
Q4
# Find diagonal matrix of a matrix
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."
Q5
# Find modal matrix of a matrix
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."
Q6
# Find diagonal & modal matrix of a matrix
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."
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
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)
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 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)
PRACTICAL : 10
A_sym = sp.Matrix(A)
b_sym = sp.Matrix(b)
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)
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)
return x