0% found this document useful (0 votes)
13 views

2023MT13122_Maths_Assignment_1

The document details the implementation of algorithms for solving the Reduced Row Echelon Form (RREF) and finding the inverse of a matrix using Gauss-Jordan elimination in Python with NumPy. It includes code snippets, explanations of steps involved, and console outputs demonstrating the processes. Additionally, it checks if a set of vectors forms a basis for R3 and finds the rank of a matrix.

Uploaded by

Oracle Java
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)
13 views

2023MT13122_Maths_Assignment_1

The document details the implementation of algorithms for solving the Reduced Row Echelon Form (RREF) and finding the inverse of a matrix using Gauss-Jordan elimination in Python with NumPy. It includes code snippets, explanations of steps involved, and console outputs demonstrating the processes. Additionally, it checks if a set of vectors forms a basis for R3 and finds the rank of a matrix.

Uploaded by

Oracle Java
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/ 22

Assignment - I

Name: RAJASEKAR PV

ID: 2023MT13122

The code is solved using the Eclipse IDE Editor using the NumPy Library.

Steps involved in solving the RREF is


1. Find the pivot row and swap
2. Make the pivot element 1
3. Eliminate other rows
Code Snippet:
def rref(matrix):

rows, cols = matrix.shape

row = 0

for col in range(cols):

if row >= rows:

break

# Find the pivot row and swap

pivot_row = np.argmax(np.abs(matrix[row:, col])) + row

matrix[[row, pivot_row]] = matrix[[pivot_row, row]]

# Make the pivot element 1

pivot = matrix[row, col]

if pivot != 0:

matrix[row] = matrix[row] / pivot

# Eliminate other rows

for r in range(rows):

if r != row:

matrix[r] -= matrix[r, col] * matrix[row]

row += 1

return matrix

# Get the RREF of the matrix

rref_matrix = rref(matrix.copy())

# Display the intermediate and final solutions

print("Intermediate Steps:")

print(matrix)

print("\nReduced Row-Echelon Form (RREF):")

print(rref_matrix)
Output Screen Shot:
Code for Gauss Elimination:

import numpy as np

def gauss_jordan_inverse(matrix):

"""

Finds the inverse of a matrix using Gauss-Jordan elimination.

Args:

matrix: A numpy array representing the square matrix.

Returns:

A numpy array representing the inverse matrix, or None if the matrix


is singular.

"""

n = matrix.shape[0]

augmented_matrix = np.concatenate((matrix, np.identity(n)), axis=1)

print("Initial Augmented Matrix:\n", augmented_matrix)

# Forward Elimination

for i in range(n):

# Find pivot

if augmented_matrix[i, i] == 0:

for j in range(i + 1, n):

if augmented_matrix[j, i] != 0:
augmented_matrix[[i, j]] = augmented_matrix[[j, i]] #swap
rows

print(f"Swapped rows {i+1} and {j+1}:\n",


augmented_matrix)

break

else: #if no swap was possible, matrix is singular

print("Matrix is singular (no inverse exists).")

return None

# Make pivot 1

pivot = augmented_matrix[i, i]

augmented_matrix[i] = augmented_matrix[i] / pivot

print(f"Made pivot {i+1} equal to 1:\n", augmented_matrix)

# Eliminate other entries in column i

for j in range(n):

if i != j:

factor = augmented_matrix[j, i]

augmented_matrix[j] = augmented_matrix[j] - factor *


augmented_matrix[i]

print(f"Eliminated entry ({j+1}, {i+1}):\n", augmented_matrix)

# Extract inverse

inverse = augmented_matrix[:, n:]

print("Inverse Matrix:\n", inverse)

return inverse

matrix = np.array([[0, 1, -1, 1],

[2, 2, 0, -2],
[1, 1, -2, 0],

[0, 1, 2, 0]], dtype=float)

gauss_jordan_inverse(matrix)

Explanation and Output Breakdown:

1. Initialization:

o The code imports the numpy library.

o The gauss_jordan_inverse function takes a square matrix as input.

o It creates an augmented matrix by concatenating the original


matrix with an identity matrix of the same size.

o The initial matrix is printed.

2. Forward Elimination:

o The code iterates through each row of the matrix.

o Pivot Finding: If the diagonal element (pivot) is zero, it


searches for a non-zero element below it in the same column and
swaps rows. If no non-zero element is found, the matrix is
singular (no inverse).

o Pivot Normalization: It divides the current row by the pivot


element to make the pivot equal to 1.

o Elimination: It eliminates other non-zero elements in the same


column by subtracting appropriate multiples of the pivot row from
other rows. Each step is printed.

3. Back Substitution (Implicit):

o The Gauss-Jordan method combines forward elimination and back


substitution into a single process. By eliminating elements above
the pivots as well, it directly produces the identity matrix on
the left side and the inverse on the right.

4. Inverse Extraction:

o The code extracts the right half of the augmented matrix, which
now represents the inverse of the original matrix.
o The inverse is printed.

Console Output:

Initial Augmented Matrix:

[[ 0. 1. -1. 1. 1. 0. 0. 0.]

[ 2. 2. 0. -2. 0. 1. 0. 0.]

[ 1. 1. -2. 0. 0. 0. 1. 0.]

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

Swapped rows 1 and 2:

[[ 2. 2. 0. -2. 0. 1. 0. 0.]

[ 0. 1. -1. 1. 1. 0. 0. 0.]

[ 1. 1. -2. 0. 0. 0. 1. 0.]

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

Made pivot 1 equal to 1:

[[ 1. 1. 0. -1. 0. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 1. 1. -2. 0. 0. 0. 1. 0. ]

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

Eliminated entry (2, 1):

[[ 1. 1. 0. -1. 0. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 1. 1. -2. 0. 0. 0. 1. 0. ]

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

Eliminated entry (3, 1):

[[ 1. 1. 0. -1. 0. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

[ 0. 1. 2. 0. 0. 0. 0. 1. ]]
Eliminated entry (4, 1):

[[ 1. 1. 0. -1. 0. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

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

Made pivot 2 equal to 1:

[[ 1. 1. 0. -1. 0. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

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

Eliminated entry (1, 2):

[[ 1. 0. 1. -2. -1. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

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

Eliminated entry (3, 2):

[[ 1. 0. 1. -2. -1. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

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

Eliminated entry (4, 2):

[[ 1. 0. 1. -2. -1. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[ 0. 0. -2. 1. 0. -0.5 1. 0. ]

[ 0. 0. 3. -1. -1. 0. 0. 1. ]]

Made pivot 3 equal to 1:

[[ 1. 0. 1. -2. -1. 0.5 0. 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]
[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 3. -1. -1. 0. 0. 1. ]]

Eliminated entry (1, 3):

[[ 1. 0. 0. -1.5 -1. 0.25 0.5 0. ]

[ 0. 1. -1. 1. 1. 0. 0. 0. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 3. -1. -1. 0. 0. 1. ]]

Eliminated entry (2, 3):

[[ 1. 0. 0. -1.5 -1. 0.25 0.5 0. ]

[ 0. 1. 0. 0.5 1. 0.25 -0.5 0. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 3. -1. -1. 0. 0. 1. ]]

Eliminated entry (4, 3):

[[ 1. 0. 0. -1.5 -1. 0.25 0.5 0. ]

[ 0. 1. 0. 0.5 1. 0.25 -0.5 0. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 0. 0.5 -1. -0.75 1.5 1. ]]

Made pivot 4 equal to 1:

[[ 1. 0. 0. -1.5 -1. 0.25 0.5 0. ]

[ 0. 1. 0. 0.5 1. 0.25 -0.5 0. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 0. 1. -2. -1.5 3. 2. ]]

Eliminated entry (1, 4):

[[ 1. 0. 0. 0. -4. -2. 5. 3. ]

[ 0. 1. 0. 0.5 1. 0.25 -0.5 0. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 0. 1. -2. -1.5 3. 2. ]]

Eliminated entry (2, 4):


[[ 1. 0. 0. 0. -4. -2. 5. 3. ]

[ 0. 1. 0. 0. 2. 1. -2. -1. ]

[-0. -0. 1. -0.5 -0. 0.25 -0.5 -0. ]

[ 0. 0. 0. 1. -2. -1.5 3. 2. ]]

Eliminated entry (3, 4):

[[ 1. 0. 0. 0. -4. -2. 5. 3. ]

[ 0. 1. 0. 0. 2. 1. -2. -1. ]

[ 0. 0. 1. 0. -1. -0.5 1. 1. ]

[ 0. 0. 0. 1. -2. -1.5 3. 2. ]]

Inverse Matrix:

[[-4. -2. 5. 3. ]

[ 2. 1. -2. -1. ]

[-1. -0.5 1. 1. ]

[-2. -1.5 3. 2. ]]

Console Output:
Steps:

1. Create a matrix from the vectors


2. Calculate the determinant
3. Check if the determinant is non-zero
4. Print the results.

Coding:

import numpy as np

def check_basis_r3(vectors):

"""

Checks if a set of 3 vectors forms a basis for R3 using numpy.

Args:

vectors: A list of numpy arrays, each representing a vector in R3.

"""

if len(vectors) != 3 or not all(v.shape == (3,) for v in vectors):

print("Error: Input must be a list of 3 vectors in R3.")

return False

# Create a matrix from the vectors

matrix = np.column_stack(vectors)
print("Matrix formed from the vectors:\n", matrix)

# Calculate the determinant

determinant = np.linalg.det(matrix)

print("Determinant of the matrix:", determinant)

# Check if the determinant is non-zero

if determinant != 0:

print("The vectors form a basis for R3.")

return True

else:

print("The vectors do not form a basis for R3.")

return False

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

vector2 = np.array([3, 0, 1])

vector3 = np.array([1, 1, 4])

vectors = [vector1, vector2, vector3]

check_basis_r3(vectors)

Output:

Matrix formed from the vectors:

[[ 0 3 1]

[ 1 0 1]

[-2 1 4]]

Determinant of the matrix: -17.0


The vectors form a basis for R3.

Console Output:
Coding:

import numpy as np

def find_matrix_rank(matrix):

"""

Finds the rank of a matrix using NumPy and prints each step.

Args:

matrix: A NumPy array representing the matrix.

"""

print("Original Matrix:\n", matrix)

# Perform Gaussian elimination (row reduction)

rows, cols = matrix.shape

reduced_matrix = matrix.astype(float).copy() # Ensure float for division

for i in range(rows):

# Find pivot

pivot_row = i

while pivot_row < rows and reduced_matrix[pivot_row, i] == 0:

pivot_row += 1

if pivot_row == rows:
continue # Skip to next column

if pivot_row != i:

reduced_matrix[[i, pivot_row]] = reduced_matrix[[pivot_row, i]]

# Swap rows

print(f"Swapped rows {i+1} and {pivot_row+1}:\n", reduced_matrix)

pivot = reduced_matrix[i, i]

reduced_matrix[i] = reduced_matrix[i] / pivot # Make pivot 1

print(f"Made pivot {i+1} equal to 1:\n", reduced_matrix)

for j in range(rows):

if i != j:

factor = reduced_matrix[j, i]

reduced_matrix[j] = reduced_matrix[j] - factor *


reduced_matrix[i] # Eliminate other entries in column i

print(f"Eliminated entry ({j+1}, {i+1}):\n", reduced_matrix)

# Count non-zero rows

rank = 0

for i in range(rows):

if not np.all(reduced_matrix[i] == 0):

rank += 1

print("Reduced Row Echelon Form:\n", reduced_matrix)

print("Rank of the matrix:", rank)

return rank

matrix_a = np.array([[1, 2, 0, 1, 1],


[2, 4, 1, 3, 0],

[3, 6, 2, 5, 1],

[-4, -8, 1, -3, 1]])

find_matrix_rank(matrix_a)

Output:

Original Matrix:

[[ 1 2 0 1 1]

[ 2 4 1 3 0]

[ 3 6 2 5 1]

[-4 -8 1 -3 1]]

Made pivot 1 equal to 1:

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

[ 2. 4. 1. 3. 0.]

[ 3. 6. 2. 5. 1.]

[-4. -8. 1. -3. 1.]]

Eliminated entry (2, 1):

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

[ 0. 0. 1. 1. -2.]

[ 3. 6. 2. 5. 1.]

[-4. -8. 1. -3. 1.]]

Eliminated entry (3, 1):

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

[ 0. 0. 1. 1. -2.]

[ 0. 0. 2. 2. -2.]

[-4. -8. 1. -3. 1.]]

Eliminated entry (4, 1):


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

[ 0. 0. 1. 1. -2.]

[ 0. 0. 2. 2. -2.]

[ 0. 0. 1. 1. 5.]]

Made pivot 3 equal to 1:

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

[ 0. 0. 1. 1. -2.]

[ 0. 0. 1. 1. -1.]

[ 0. 0. 1. 1. 5.]]

Eliminated entry (1, 3):

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

[ 0. 0. 1. 1. -2.]

[ 0. 0. 1. 1. -1.]

[ 0. 0. 1. 1. 5.]]

Eliminated entry (2, 3):

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

[ 0. 0. 0. 0. -1.]

[ 0. 0. 1. 1. -1.]

[ 0. 0. 1. 1. 5.]]

Eliminated entry (4, 3):

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

[ 0. 0. 0. 0. -1.]

[ 0. 0. 1. 1. -1.]

[ 0. 0. 0. 0. 6.]]

Reduced Row Echelon Form:

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

[ 0. 0. 0. 0. -1.]

[ 0. 0. 1. 1. -1.]
[ 0. 0. 0. 0. 6.]]

Rank of the matrix: 4

Console Screen Shot:


Steps:

compute_svd function:

 Takes a NumPy array representing the matrix as input.

 Print Original Matrix: Prints the input matrix.

 Compute SVD:

o Uses np.linalg.svd(matrix) to compute the Singular Value


Decomposition.

o The function returns three matrices:

 U: The left singular vectors (an orthogonal matrix).

 S: The singular values (a 1D array).

 V_T: The transpose of the right singular vectors (an


orthogonal matrix).

 Print U, S, and V_T: Prints the U, S, and V_T matrices.

 Reconstruction (Verification):

o Creates a diagonal matrix Sigma with the singular values from S on


the diagonal. The dimensions of Sigma match the original matrix.

o Reconstructs the original matrix by multiplying U, Sigma, and V_T


using the @ operator (matrix multiplication).

o Prints the reconstructed matrix.


Coding:

import numpy as np

def compute_svd(matrix):

"""

Computes the Singular Value Decomposition (SVD) of a matrix using NumPy.

Args:

matrix: A NumPy array representing the matrix.

"""

print("Original Matrix:\n", matrix)

# Compute SVD

U, S, V_T = np.linalg.svd(matrix)

print("\nU Matrix (Left Singular Vectors):\n", U)

print("\nS Vector (Singular Values):\n", S)

print("\nV_T Matrix (Right Singular Vectors Transposed):\n", V_T)

# Reconstruct the matrix to verify

Sigma = np.zeros(matrix.shape)

np.fill_diagonal(Sigma, S)

reconstructed_matrix = U @ Sigma @ V_T

print("\nReconstructed Matrix (U * Sigma * V_T):\n", reconstructed_matrix)

matrix_a = np.array([[3, 1, 1, 0],

[1, 2, 2, -1]])
compute_svd(matrix_a)

Output:

Original Matrix:

[[ 3 1 1 0]

[ 1 2 2 -1]]

U Matrix (Left Singular Vectors):

[[-0.73186305 -0.68145174]

[-0.68145174 0.73186305]]

S Vector (Singular Values):

[4.18543121 1.86605616]

V_T Matrix (Right Singular Vectors Transposed):

[[-0.68739414 -0.50049002 -0.50049002 0.16281518]

[-0.70335084 0.41921266 0.41921266 -0.39219776]

[-0.03314926 -0.64543234 0.74488012 0.1657463 ]

[-0.17801127 0.3964689 0.13756491 0.89005634]]

Reconstructed Matrix (U * Sigma * V_T):

[[ 3.00000000e+00 1.00000000e+00 1.00000000e+00 -1.16258748e-16]

[ 1.00000000e+00 2.00000000e+00 2.00000000e+00 -1.00000000e+00]]

You might also like