Finding the rank of a matrix
Here’s a Java program that calculates the rank of a matrix using Gaussian elimination:
import java.util.Arrays; public class MatrixRank { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int rank = calculateRank(matrix); System.out.println("Rank of the matrix: " + rank); } public static int calculateRank(int[][] matrix) { int rowCount = matrix.length; int colCount = matrix[0].length; int rank = Math.min(rowCount, colCount); for (int row = 0; row < rank; row++) { // Check if diagonal element is zero if (matrix[row][row] != 0) { for (int col = 0; col < rowCount; col++) { if (col != row) { // Making all other elements of current column zero int multiplier = matrix[col][row] / matrix[row][row]; for (int i = 0; i < rank; i++) { matrix[col][i] -= matrix[row][i] * multiplier; } } } } else { boolean reduced = false; // Find a non-zero element in the same column for (int i = row + 1; i < rowCount; i++) { if (matrix[i][row] != 0) { // Swap rows to make the non-zero element at the diagonal int[] temp = matrix[row]; matrix[row] = matrix[i]; matrix[i] = temp; reduced = true; break; } } if (!reduced) { // All elements below current row are zero, reduce rank rank--; for (int col = 0; col < rowCount; col++) { matrix[col][row] = matrix[col][rank]; } } row--; } } return rank; } }
In this program, the `calculateRank` method takes a 2D matrix as input and returns the rank of the matrix. It uses the Gaussian elimination algorithm to reduce the matrix to row-echelon form. The rank is determined by counting the number of non-zero rows in the row-echelon form.
In the `main` method, a sample matrix is provided, and the `calculateRank` method is called to find the rank of the matrix. The result is then printed to the console. Feel free to modify the sample matrix or input your own matrix to test the program.
No comments yet! You be the first to comment.