Home Tutorial Java Core Find determinant of a matrix in Java Programming

 
 

Find determinant of a matrix in Java Programming
Posted on: November 9, 2009 at 12:00 AM
In this section, you will learn how to determine the determinant of 2x2 matrix.

Find determinant of a matrix in Java Programming

A determinant is a real number associated with every square matrix or, you can say it is a rectangular array of numbers where the number of rows and columns are equal.It is a scale factor for measure when the matrix is regarded as a linear transformation. Here we are going to find the determinant of 2x2 matrix.

In 2×2 matrix,
a[0][0] a[0][1]
a[1][0] a[1][1]
determinant = a[0][0] * a[1][1] - a[0][1] * a[1][0];

Here is the code:

public class Determinant {
	public int determinant(int[][] arr) {
		int result = 0;
		if (arr.length == 1) {
			result = arr[0][0];
			return result;
		}
		if (arr.length == 2) {
			result = arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0];
			return result;
		}
		for (int i = 0; i < arr[0].length; i++) {
			int temp[][] = new int[arr.length - 1][arr[0].length - 1];

			for (int j = 1; j < arr.length; j++) {
				for (int k = 0; k < arr[0].length; k++) {

					if (k < i) {
						temp[j - 1][k] = arr[j][k];
					} else if (k > i) {
						temp[j - 1][k - 1] = arr[j][k];
					}
				}
			}
			result += arr[0][i] * Math.pow(-1, (int) i) * determinant(temp);
		}
		return result;
	}

	public static void main(String[] args) {
		int array[][] = { { 5, 6 }, { 8, 9 } };
		Determinant d = new Determinant();
		int result = d.determinant(array);
		System.out.println(result);
	}
}

Related Tags for Find determinant of a matrix in Java Programming:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.