import numpy as np from numpy.linalg import matrix_rank from numpy.linalg import det def mySweep(A, m): if A.shape[0] != A.shape[1]: return ('input matrix is not a squared matrix') elif A.shape[0] != matrix_rank(A): return ('input matrix is not invertible') else: B = np.copy(A) n = B.shape[0] for k in range(m): for i in range(n): for j in range(n): if i != k and j != k: B[i,j] = B[i,j]- B[i,k]*B[k,j]/B[k,k] for i in range(n): if i != k: B[i,k] = B[i,k]/B[k,k] for j in range(n): if j != k: B[k,j] = B[k,j]/B[k,k] B[k,k] = - 1/B[k,k] return B def mySweepRev(A, m): if A.shape[0] != A.shape[1]: return ('input matrix is not a squared matrix') elif A.shape[0] != matrix_rank(A): return ('input matrix is not invertible') else: B = np.copy(A) n = B.shape[0] for k in range(m): for i in range(n): for j in range(n): if i != k and j != k: B[i,j] = B[i,j]- B[i,k]*B[k,j]/B[k,k] for i in range(n): if i != k: B[i,k] = - B[i,k]/B[k,k] for j in range(n): if j != k: B[k,j] = - B[k,j]/B[k,k] B[k,k] = - 1/B[k,k] return B def myGaussJordan(A, m): if A.shape[0] != A.shape[1]: return ('input matrix is not a squared matrix') elif A.shape[0] != matrix_rank(A): return ('input matrix is not invertible') else: n = A.shape[0] B = np.hstack((A, np.identity(n))) for k in range(m): a = B[k, k] for j in range(n * 2): B[k, j] = B[k, j] / a for i in range(n): if i != k: a = B[i, k] for j in range(n * 2): B[i, j] = B[i, j] - B[k, j] * a; return B[:, n:2 * n] def myGaussJordanVec(A, m): if A.shape[0] != A.shape[1]: return ('input matrix is not a squared matrix') elif A.shape[0] != matrix_rank(A): return ('input matrix is not invertible') else: n = A.shape[0] B = np.hstack((A, np.identity(n))) for k in range(m): B[k, :] = B[k,] / B[k, k] for i in range(n): if i != k: B[i,] = B[i,] - B[k,] * B[i, k] return B[:, n:2 * n] def mySweepDet(A, m): if A.shape[0] != A.shape[1]: return ('input matrix is not a squared matrix') elif A.shape[0] != matrix_rank(A): return ('input matrix is not invertible') else: B = np.copy(A) D = 1 n = B.shape[0] for k in range(m): for i in range(n): for j in range(n): if i != k and j != k: B[i,j] = B[i,j]- B[i,k]*B[k,j]/B[k,k] for i in range(n): if i != k: B[i,k] = - B[i,k]/B[k,k] for j in range(n): if j != k: B[k,j] = B[k,j]/B[k,k] D = D * B[k,k] B[k,k] = 1/B[k,k] return D A = np.array([[1,2,3],[7,11,13],[17,21,23]], dtype=float).T print('sweep operator:\n',mySweep(A, 3)) print('reverse sweep operator:\n',mySweepRev(mySweep(A, 3),3)) print('GaussJordan:\n',myGaussJordan(A, 3)) print('GaussJordan vectorized version:\n',myGaussJordanVec(A, 3)) print('computing the determinant of a matrix using the det function:',det(A)) print('computing the determinant of a matrix using the sweep operator:',mySweepDet(A, 3))
|