MTH202 Worksheet 6¶
In [1]:
import numpy as np
In [2]:
def RREF(A, showsteps='No'):
m, n = A.shape
A = A.astype(float)
if showsteps=='Yes':
print(f"Input matrix \nA = \n{A}\n\n")
I = 0
for j in range(n):
if showsteps=='Yes':
print(f"-----CONSIDER COL {j}-----\n")
for i in range(m):
if i >= I and A[i,j] != 0:
if showsteps=='Yes':
print(f"CONSIDER ROW {I}\nSWAP rows {i} and {I}:")
A[[I,i]] = A[[i,I]]
if showsteps=='Yes':
print(f"A = \n{A}")
A[I,:] /= A[I,j]
A[I+1:,:] -= A[I+1:,[j]] * A[I,:]
A[:I,:] -= A[:I,[j]] * A[I,:] # This line is added from the code in 5.1.
if showsteps=='Yes':
print(f"PIVOT at ({I},{j}): \nA = \n{A}\n\nROW {I} DONE.")
I += 1
break
if showsteps=='Yes':
print(f"COL {j} DONE.\n")
if showsteps=='Yes':
print("-----ALL COLs DONE-----\n")
print(f"RREF(A) = \n{A}")
return A
Problem 1¶
The above block defines a function RREF, which is used to find the RREF of a given matrix.
Instruction
Consider a matrix equation $Ax = b$.
Write a function solnum that inputs the matrix A and vector b, then print the number of solutions of $Ax = b$.
Expected behavior
- When there is a unique solution.
in: solnum(A,b)
out: Ax = b has a unique solution.
- When there are multiple solutions.
in: solnum(A,b)
out: Ax = b has multiple solutions.
- When there is no solution.
in: solnum(A,b)
out: Ax = b has no solution.
In [3]:
# Write your function here.
def solnum(A,b):
"""
The inputs A and b should have matching dimensions.
The following format should hold.
A.shape = (m,n) and b.shape = (m,1).
"""
m, n = A.shape
A_rref = RREF(A)
Ab = np.hstack((A,b))
Ab_rref = RREF(Ab)
rank_A = 0
rank_Ab = 0
for i in range(m):
if (A_rref[i] != np.zeros((n,))).any():
rank_A += 1
if (Ab_rref[i] != np.zeros((n+1,))).any():
rank_Ab += 1
print(rank_A)
print(rank_Ab)
if rank_A != rank_Ab:
print("Ax = b has no solution.")
elif rank_A == rank_Ab and rank_A == n:
print("Ax = b has a unique solution.")
else:
print("Ax = b has multiple solutions.")
Tests¶
In [4]:
A1 = np.array([[1,1,1],
[0,0,1],
[0,1,0]])
A2 = np.array([[1,1,1],
[0,0,0],
[1,1,1]])
A3 = np.array([[1,1,1],
[0,0,0],
[1,0,0]])
b = np.array([[3,0,1]]).T
In [5]:
solnum(A1,b) # unique solution
3 3 Ax = b has a unique solution.
In [6]:
solnum(A2,b) # no solution
1 2 Ax = b has no solution.
In [7]:
solnum(A3,b) # multiple solution
2 2 Ax = b has multiple solutions.