Question: Please generalize this code to work for a matrix of any dimension: def isSingular ( A ) : B = np . array ( A

Please generalize this code to work for a matrix of any dimension:
def isSingular(A) :
B = np.array(A,dtype=np.float_) # Lets make a copy as we are going to change this matrix
try:
alterRowZero(B)
print(B)
alterRowOne(B)
print(B)
alterRowTwo(B)
print(B)
alterRowThree(B)
print(B)
except ItIsSingular:
return True
return False
#this is our error class. no need to make any changes here
class ItIsSingular(Exception): pass
#Remember that for the first row, all we need is the first element to be 1.
#We can do it by dividing the whole row by the value of the element i.e., A[0,0]
#However if A[0,0] is zero, then we are in trouble.. so need to test for that.
#if that is the case we can add the lower row one by one to make sure we have a non zero first element.
# Do not edit this.
def alterRowZero(A) :
if A[0,0]==0 :
A[0]= A[0]+ A[1]
if A[0,0]==0 :
A[0]= A[0]+ A[2]
if A[0,0]==0 :
A[0]= A[0]+ A[3]
if A[0,0]==0 :
raise ItIsSingular()
A[0]= A[0]/ A[0,0]
return A
#We need to make the element below the diagonal element zero i.e. A[1,0]
# Next make A[1,1]=1
# We'll divide the row by the value of A[1,1].
# Do the zero test again
# There is no need to edit this function.
def alterRowOne(A) :
A[1]= A[1]- A[1,0]* A[0]
if A[1,1]==0 :
A[1]= A[1]+ A[2]
A[1]= A[1]- A[1,0]* A[0]
if A[1,1]==0 :
A[1]= A[1]+ A[3]
A[1]= A[1]- A[1,0]* A[0]
if A[1,1]==0 :
raise ItIsSingular()
A[1]= A[1]/ A[1,1]
return A
# Complete this function
def alterRowTwo(A) :
# Make the required elements in row two to zero (hint: there are 2 of them).
A[2]= A[2]- A[2,0]* A[0]
A[2]= A[2]- A[2,1]* A[1]
# zero test
if A[2,2]==0:
A[2]= A[2]+ A[3]
A[2]= A[2]- A[2,0]* A[0]
# make sub diagonal elements zero
if A[2,2]==0:
raise ItIsSingular()
# Finally set the diagonal element to one by dividing the whole row by that element.
A[2]= A[2]/ A[2,2]
return A
# You should also complete this function
# Follow the instructions inside the function at each comment.
def alterRowThree(A) :
# Insert code below to set the sub-diagonal elements of row three to zero.
#Setting elements in row three to zero
A[3]= A[3]- A[3,0]* A[0]
A[3]= A[3]- A[3,1]* A[1]
A[3]= A[3]- A[3,2]* A[2]
#sub-diagonal elements zero
if A[3,3]==0:
raise ItIsSingular()
#Sub-diagonal elements to one
A[3]= A[3]/ A[3,3]
return A

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!