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

Assignment -4

The document is a Python notebook that implements matrix algebra operations using NumPy, including input for matrix creation, calculation of dimensions, determinant, inverse, trace, rank, eigenvalues, and eigenvectors. It also allows for solving systems of linear equations by inputting coefficient and constant matrices. The notebook provides user prompts for data entry and outputs the results of the calculations.

Uploaded by

basmah.basheer
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)
4 views6 pages

Assignment -4

The document is a Python notebook that implements matrix algebra operations using NumPy, including input for matrix creation, calculation of dimensions, determinant, inverse, trace, rank, eigenvalues, and eigenvectors. It also allows for solving systems of linear equations by inputting coefficient and constant matrices. The notebook provides user prompts for data entry and outputs the results of the calculations.

Uploaded by

basmah.basheer
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/ 6

Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

import numpy as np

def matrix_algebra():
print("Enter the matrix row by row")
rows = []
while True:
row = input()
if row.lower() == 'done':
break
try:
rows.append([float(num) for num in row.strip().split()])
except ValueError:
print("Invalid input. Please enter numbers only.")
return

try:
matrix = np.array(rows)
print("\nMatrix:")
print(matrix)

# a. Dimensions
print(f"\na. Dimensions: {matrix.shape}")

# Check if square for determinant and inverse


if matrix.shape[0] == matrix.shape[1]:
# b. Determinant
det = np.linalg.det(matrix)
print(f"b. Determinant: {det}")

# c. Inverse (if determinant is non-zero)


if det != 0:
inv = np.linalg.inv(matrix)
print(f"c. Inverse:\n{inv}")
else:
print("c. Inverse: Not defined (determinant is zero)")
else:
print("b. Determinant: Not defined (matrix is not square)")
print("c. Inverse: Not defined (matrix is not square)")

# d. Trace and Rank


if matrix.shape[0] == matrix.shape[1]:
trace = np.trace(matrix)
print(f"d. Trace: {trace}")
else:
print("d. Trace: Not defined (matrix is not square)")

rank = np.linalg.matrix_rank(matrix)
print(f" Rank: {rank}")

# e. Eigenvalues and eigenvectors (only for square matrices)


if matrix.shape[0] == matrix.shape[1]:
eigenvalues, eigenvectors = np.linalg.eig(matrix)

1 of 6 8/4/25, 16:31
Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

eigenvalues, eigenvectors = np.linalg.eig(matrix)


print(f"e. Eigenvalues: {eigenvalues}")
print(f" Eigenvectors:\n{eigenvectors}")
else:
print("e. Eigenvalues and Eigenvectors: Not defined (matrix is not square)
# f. The second row of the matrix
if matrix.shape[0] >= 2:
second_row = matrix[1, :]
print("Second row of the matrix:", second_row)
else:
print("The matrix does not have a second row.")

# g. Second and third columns of the matrix


if matrix.shape[1] >= 3:
second_and_third_columns = matrix[:, 1:3]
print("Second and third columns of the matrix:\n", second_and_third_column
elif matrix.shape[1] == 2:
second_column = matrix[:, 1]
print("Second column of the matrix:", second_column)
print("The matrix does not have a third column.")
else:
print("The matrix does not have second or third columns.")

except Exception as e:
print(f"An error occurred: {e}")

# Run the program


matrix_algebra()

Enter the matrix row by row


2 3 4
1 2 3
5 6 7
done

Matrix:
[[2. 3. 4.]
[1. 2. 3.]
[5. 6. 7.]]

a. Dimensions: (3, 3)
b. Determinant: -1.7763568394002396e-15
c. Inverse:
[[ 2.25179981e+15 -1.68884986e+15 -5.62949953e+14]
[-4.50359963e+15 3.37769972e+15 1.12589991e+15]
[ 2.25179981e+15 -1.68884986e+15 -5.62949953e+14]]
d. Trace: 11.0
Rank: 2
e. Eigenvalues: [ 1.17649820e+01 -8.47741729e-16 -7.64982043e-01]
Eigenvectors:
[[-0.4396837 -0.40824829 -0.30960769]
[-0.30460397 0.81649658 -0.64553142]
[-0.84492288 -0.40824829 0.69816349]]
Second row of the matrix: [1. 2. 3.]
Second and third columns of the matrix:

2 of 6 8/4/25, 16:31
Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

[[3. 4.]
[2. 3.]
[6. 7.]]

Double-click (or enter) to edit

Start coding or generate with AI.

import numpy as np

coeffrows = []
constantrows = []

while True:
coeffrow = input()
if coeffrow.lower() == 'done':
break
row_val = [float(x) for x in coeffrow.replace(',', '').split()]
coeffrows.append(row_val)

A = np.array(coeffrows)
print("\n---- Coefficient Matrix A ----")
print(A)

while True:
constantrow = input()
if constantrow.lower() == "done":
break
row_val2 = [float(x) for x in constantrow.replace(',', '').split()]
constantrows.append(row_val2)

B = np.array(constantrows)
print("\n---- Constant Matrix B ----")
print(B)

if A.shape[0] != A.shape[1]:
print("\nError: Matrix A must be square to invert.")
elif A.shape[0] != B.shape[0]:
print("\nError: Matrix A and B dimensions do not match.")
else:
A_inv = np.linalg.inv(A)
print("\n---- Inverse of Matrix A ----")
print(A_inv)

Y = np.matmul(A_inv, B)
print("\n---- Solution [x y z u w] ----")
print(Y)

1.5 -2 1 3 0.5
3 1 -1 4 -3
2 6 -3 -1 3

3 of 6 8/4/25, 16:31
Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

2 6 -3 -1 3
5 2 4 -2 6
-3 3 2 5 4
done
[[ 1.5 -2. 1. 3. 0.5]
[ 3. 1. -1. 4. -3. ]
[ 2. 6. -3. -1. 3. ]
[ 5. 2. 4. -2. 6. ]
[-3. 3. 2. 5. 4. ]]
7.5
16
78
71
54
done
[[ 7.5]
[16. ]
[78. ]
[71. ]
[54. ]]
[[ 0.09280742 0.07347254 0.03789637 0.0641918 -0.0812065 ]
[-0.30742459 0.15245553 -0.02136504 0.05819799 0.08149652]
[-0.31670534 0.14510828 -0.22515468 0.15177881 0.08961717]
[ 0.14037123 0.04862722 0.01981825 -0.0404099 0.06467517]
[ 0.28306265 -0.19257541 0.13225058 -0.02088167 0.00232019]]
[[ 5.]
[ 7.]
[-2.]
[ 4.]
[ 8.]]

#Solve the system of equations

#1.5x − 2y + z + 3u + 0.5w = 7.5


#3x + y − z + 4u − 3w = 16
#2x + 6y − 3z − u + 3w = 78
#5x + 2y + 4z − 2u + 6w = 71
#−3x + 3y + 2z + 5u + 4w = 54

import numpy as np
coeffrows=[]
constantrows=[]
while True:
coeffrow=input()
if coeffrow.lower()=='done':
break
row_val = [float(x) for x in coeffrow.split()]
coeffrows.append(row_val)
A = np.array(coeffrows)
print("\n---- Coefficient Matrix A ----")
print(A)

while True:
constantrow=input()

if constantrow.lower()=="done":

4 of 6 8/4/25, 16:31
Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

break
row_val2 = [float(x) for x in constantrow.split()]
constantrows.append(row_val2)
B = np.array(constantrows)
print("\n---- Constant Matrix B ----")
print(B)
X = np.linalg.inv(A)
print("\n---- Inverse of Matrix A ----")
print(X)
Y=np.linalg.matmul(X,B)
print("\n---- Solution Vector [x y z u w] ----")
print(Y)

1.5 -2 1 3 0.5
3 1 -1 4 -3
2 6 -3 -1 3
5 2 4 -2 6
-3 3 2 5 4
done

---- Coefficient Matrix A ----


[[ 1.5 -2. 1. 3. 0.5]
[ 3. 1. -1. 4. -3. ]
[ 2. 6. -3. -1. 3. ]
[ 5. 2. 4. -2. 6. ]
[-3. 3. 2. 5. 4. ]]
7.5
16
78
71
54
done

---- Constant Matrix B ----


[[ 7.5]
[16. ]
[78. ]
[71. ]
[54. ]]

---- Inverse of Matrix A ----


[[ 0.09280742 0.07347254 0.03789637 0.0641918 -0.0812065 ]
[-0.30742459 0.15245553 -0.02136504 0.05819799 0.08149652]
[-0.31670534 0.14510828 -0.22515468 0.15177881 0.08961717]
[ 0.14037123 0.04862722 0.01981825 -0.0404099 0.06467517]
[ 0.28306265 -0.19257541 0.13225058 -0.02088167 0.00232019]]

---- Solution Vector [x y z u w] ----


[[ 5.]
[ 7.]
[-2.]
[ 4.]
[ 8.]]

Start coding or generate with AI.

5 of 6 8/4/25, 16:31
Matrix Algebra.ipynb - Colab https://colab.research.google.com/drive/10WvOPJ6VifGLb...

6 of 6 8/4/25, 16:31

You might also like