#! /usr/bin/env python3 # def is_rref_test ( ): #*****************************************************************************80 # ## is_rref_test() tests is_rref(). # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 04 December 2024 # # Author: # # John Burkardt # import numpy as np print ( '' ) print ( 'is_rref_test():' ) print ( ' is_rref() reports whether a matrix is in reduced row echelon format.' ) # # Zero rows must come last. # A0 = np.array ( [ \ [ 1, 0, 0, 9, 4 ], \ [ 0, 0, 1, 0, 8 ], \ [ 0, 0, 0, 0, 0 ], \ [ 0, 0, 0, 1, 0 ] \ ] ) # # First nonzero must be to right of first nonzero in previous row. # A1 = np.array ( [ \ [ 1, 0, 0, 9, 4 ], \ [ 0, 0, 0, 1, 0 ], \ [ 0, 0, 1, 0, 8 ], \ [ 0, 0, 0, 0, 0 ] \ ] ) # # First nonzero must be a 1. # A2 = np.array ( [ \ [ 1, 0, 0, 9, 4 ], \ [ 0, 1, 0, 2, 8 ], \ [ 0, 0, 3, 0, 0 ], \ [ 0, 0, 0, 0, 0 ] \ ] ) # # First nonzero must only nonzero in its column. # A3 = np.array ( [ \ [ 1, 0, 3, 9, 4 ], \ [ 0, 1, 0, 2, 8 ], \ [ 0, 0, 1, 0, 0 ], \ [ 0, 0, 0, 0, 0 ] \ ] ) # # RREF example. # A4 = np.array ( [ \ [ 1, 0, 3, 0, 4 ], \ [ 0, 1, 2, 0, 8 ], \ [ 0, 0, 0, 1, 0 ], \ [ 0, 0, 0, 0, 0 ] \ ] ) for A, A_name in [ [ A0, 'A0' ], [ A1, 'A1' ], [ A2, 'A2' ], [ A3, 'A3' ], [ A4, 'A4' ] ]: print ( '' ) print ( ' ' + A_name + ':' ) print ( A ) print ( ' is_rref(' + A_name + ') = ', is_rref ( A ) ) return def is_rref ( A ): #*****************************************************************************80 # ## is_rref() determines if a matrix is in reduced row echelon format. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 14 December 2024 # # Author: # # John Burkardt # # Input: # # A[m,n]: a numpy array defining a matrix. # # Output: # # is_ref: True if A is in reduced row echelon form. # m, n = A.shape c = -1 for r in range ( 0, m ): # # Increment the first legal column for next pivot. # c = c + 1 # # Search for pivot p in this row. # If none, set p = n. # p = n for j in range ( 0, n ): if ( A[r,j] != 0.0 ): p = j break # # If p == n, go to next row. # if ( p == n ): c = n - 1; continue # # If p is too early, fail. # if ( p < c ): print ( ' Nonzero A[', r, ',', p, '] occurs before column ', c, '.' ) return False # # Accept p as new c. # c = p # # If A(r,c) is not 1, fail # if ( A[r,c] != 1.0 ): print ( ' A[', r, ',', c, '] is not 1.0.' ) return False # # If A(r,c) is not the only nonzero in column c, fail # for i in range ( 0, m ): if ( i != r ): if ( A[i,c] != 0.0 ): print ( ' A[',i, ',', c, '] should be zero.' ) return False return True if ( __name__ == "__main__" ): is_rref_test ( )