Related Tags

matrix
data structures
communitycreator

# How to check if a given matrix is diagonally dominant

abhilash

### What is a diagonally dominant matrix?

A square matrix is said to be diagonally dominant if the magnitude of the diagonal element in a row is greater than or equal to the sum of the magnitudes of all the other non-diagonal elements in that row for each row of the matrix.

For example, consider the following matrix:

[[7, 3, -2],
[6, 15, -3],
[5, 5, 10]]


Row 1: 7 > 5 (3 + |-2|)
Row 2: 15 > 9 (6 + |-3|)
Row 3: 10 >= 10 (5 + 5)

If the diagonal element of every row is greater or equal to the sum of the non-diagonal elements of the same row, then the matrix is a diagonally dominant matrix.

### Algorithm

The steps of the algorithm are as follows:

1. For every row of the matrix do the following steps:
1. Find the sum of all the elements in the row.
2. Subtract the diagonal elements in the row from the sum above to find the sum of the non-diagonal elements in the row.
3. If the diagonal element is less than the sum from Step 2, then the matrix is not a diagonally dominant matrix.
2. Otherwise, the matrix is a diagonally dominant matrix as every row satisfies the condition.

### Implementation of the algorithm

import java.util.Arrays;

public class Main {

private static void printMatrix(int[][] matrix){
// Convert every row of the matrix to a string using Arrays.toString method
// and the print the row string to console
for(int[] row: matrix){
System.out.println(Arrays.toString(row));
}
}

private static boolean checkDiagonalDominantMatrix(int[][] matrix){

// variable i to go through every row
for(int i=0;i < matrix.length; i++){
// initialize a variable to hold the sum
int rowSum = 0;
// loop through every column in the row
for (int j = 0; j < matrix[i].length; j++)
// add the absolute sum of the element to the sum variable
rowSum += Math.abs(matrix[i][j]);

// subtract the diagonal element from the row sum
rowSum -= Math.abs(matrix[i][i]);

// check the condition for diagonal dominance
if (Math.abs(matrix[i][i]) < rowSum)
return false;
}
return true;
}

private static void wrapper(int[][] matrix){
// print the matrix
printMatrix(matrix);
if(checkDiagonalDominantMatrix(matrix)) System.out.println("The matrix is a diagonally dominant matrix");
else System.out.println("The matrix is not a diagonally dominant matrix");
}

public static void main(String[] args){
// Define the matrix to be tested
int[][] matrix = {{7, 3, -2},{6, 15, -3},{5, 5, 10}};
wrapper(matrix);
System.out.println("-------------");
int[][] matrix1 = {{4, 0},{5, -4}};
wrapper(matrix1);
}
}
Code to check if a matrix is Diagonally Dominant

RELATED TAGS

matrix
data structures
communitycreator

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 