How to check if a given matrix is a diagonal matrix

What is a diagonal matrix?

A diagonal matrix is a square matrix in which all members are zero, except the major diagonal elements.

Example

Dimension Matrix
2 x 2 [[34, 0], [0, -4]]
3 x 3 [[4, 0, 0], [0, -1, 0], [0, 0, -3]]

Algorithm

  1. Start looping over the elements of the matrix.

  2. For every element, check the following:

    a. If the row number is equal to the column number, then it’s a diagonal element. Check if the value is not equal to zero.

    b. If the row number is not equal to the column number, then it’s not a diagonal element. Check if the value is zero.

    c. If any of the above conditions are false, then the matrix is not a diagonal matrix, and the program returns false.

    d. Otherwise, it returns true, indicating that the matrix is a diagonal matrix.

Code

import java.util.Arrays;
public class Main {
private static void printMatrix(int[][] matrix){
for(int[] row: matrix){
System.out.println(Arrays.toString(row));
}
}
private static boolean checkDiagonalMatrix(int[][] matrix){
for(int i=0; i<matrix.length;i++)
for(int j=0; j<matrix[i].length;j++){
if((i == j && matrix[i][j] == 0) || (i != j && matrix[i][j] != 0)) return false;
}
return true;
}
private static void wrapper(int[][] matrix){
printMatrix(matrix);
if(checkDiagonalMatrix(matrix)) System.out.println("The matrix is a diagonal matrix");
else System.out.println("The matrix is not a diagonal matrix");
}
public static void main(String[] args){
int[][] matrix = {{4, -1},{15, -4}};
wrapper(matrix);
System.out.println("-------------");
int[][] matrix1 = {{4, 0},{0, -4}};
wrapper(matrix1);
}
}

Free Resources