Finding the matrix rank using Gaussian elimination.
Here’s a Java program that uses Gaussian elimination to find the rank of a matrix:
import java.util.Arrays; public class MatrixRank { public static int findRank(double[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; int rank = Math.min(rows, columns); for (int row = 0; row < rank; row++) { if (matrix[row][row] != 0) { for (int col = 0; col < rows; col++) { if (col != row) { double multiplier = matrix[col][row] / matrix[row][row]; for (int i = 0; i < columns; i++) { matrix[col][i] -= matrix[row][i] * multiplier; } } } } else { boolean reduce = true; for (int i = row + 1; i < rows; i++) { if (matrix[i][row] != 0) { swapRows(matrix, row, i); reduce = false; break; } } if (reduce) { rank--; for (int i = 0; i < rows; i++) { matrix[i][row] = matrix[i][rank]; } } row--; } } return rank; } private static void swapRows(double[][] matrix, int row1, int row2) { double[] temp = matrix[row1]; matrix[row1] = matrix[row2]; matrix[row2] = temp; } public static void main(String[] args) { double[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int rank = findRank(matrix); System.out.println("Matrix rank: " + rank); } }
In this program, the `findRank` method takes a 2D array representing a matrix as input and returns its rank as an integer. The program implements the Gaussian elimination algorithm to reduce the matrix to row echelon form. It uses elementary row operations such as swapping rows and subtracting multiples of one row from another.
In the `main` method, we create a sample matrix and call the `findRank` method to calculate its rank. The result is then printed to the console.
Note: The program assumes that the input matrix is non-empty and rectangular (i.e., all rows have the same number of columns). You can modify the program as per your requirements.
No comments yet! You be the first to comment.