Question: Exercise 1 This exercise involves implementing the elimination method to convert a matrix into row - echelon form. As discussed in lectures, the primary approach

Exercise 1This exercise involves implementing the elimination method to convert a matrix into row-echelon form. As discussed in lectures, the primary approach involves inspecting the values along the diagonal. If they equate to 0, an attempt to swap rows should be made to obtain a non-zero value.# import numpy as npdef row_echelon_form(A, B): """ Utilizes elementary row operations to transform a given set of matrices, which represent the coefficients and constant terms of a linear system, into row echelon form. Parameters: - A (numpy.array): The input square matrix of coefficients. - B (numpy.array): The input column matrix of constant terms. Returns: numpy.array: A new augmented matrix in row echelon form with pivots as 1.""" # Before any computation, check if matrix A (coefficient matrix) has non-zero determinant. # It will be used the numpy sub library np.linalg to compute it. det_A = np.linalg.det(A) # Returns "Singular system" if determinant is zero if np.isclose(det_A,0)== True: return 'Singular system' # Make copies of the input matrices to avoid modifying the originals A = A.copy() B = B.copy() # Convert matrices to float to prevent integer division A = A.astype('float64') B = B.astype('float64') # Number of rows in the coefficient matrix num_rows = len(A) # Create the augmented matrix M (concatenate A and B) M = np.hstack((A, B.reshape(-1,1))) # Iterate over the rows. for row in range(num_rows): # Get the pivot candidate from the diagonal element pivot_candidate = M[row, row] # If pivot_candidate is zero, try to find a non-zero pivot below the current row if np.isclose(pivot_candidate, 0): for i in range(row +1, num_rows): if not np.isclose(M[i, row],0): # Swap rows M[[row, i]]= M[[i, row]] pivot_candidate = M[row, row] # Recalculate the pivot after swap break # If pivot_candidate is non-zero, scale the row to make the pivot equal to 1 if not np.isclose(pivot_candidate, 0): M[row]= M[row]/ pivot_candidate # Perform row reduction for rows below the current row for i in range(row +1, num_rows): # Get the factor to eliminate the value below the pivot factor = M[i, row] # Perform row reduction: row_to_reduce -> row_to_reduce - factor * pivot_row M[i]= M[i]- factor * M[row] return M

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!