Diagonally Dominant Matrix in C++?


A matrix is said to be diagonally dominant matrix if for every matrix row, the diagonal entry magnitude of the row is larger than or equal to the sum of the magnitudes of every other non-diagonal entry in that row.

Let us first define a constant int variable N with value 3 which represents our matrix dimensions.

const int N = 3;

The isDDM(int mat[N][N], int n) is a Boolean function that takes a copy of our matrix and the size of our matrix. Inside we iterate the rows and columns of our matrix using nested for loop. We then find the sum of each row for each column and add it to our sum variable.

bool isDDM(int mat[N][N], int n){
for (int i = 0; i < n; i++){
   int sum = 0;
   for (int j = 0; j < n; j++)
      sum += abs(mat[i][j]);

Next, we remove the sum of diagonal elements from the current sum.

sum -= abs(mat[i][i]);

Next, we check if any of the diagonal element is less than the sum or not. If any one of them is less than sum then we return false and exit our loop and function otherwise the after completion of loop we return true as none of the elements are less than sum.

bool isDDM(int mat[N][N], int n){
for (int i = 0; i < n; i++){
   int sum = 0;
   for (int j = 0; j < n; j++)
      sum += abs(mat[i][j]);
      sum -= abs(mat[i][i]);
   if (abs(mat[i][i]) < sum)
      return false;
   }
   return true;
}

Finally, based upon the value return we display whether it is a diagonally dominant matrix or not in our main function.

if(isDDM(mat,matSize)){
   cout << "yes,its a diagonally dominant matrix";
} else {
   cout << "NO, its not a diagonally dominant matrix";
}

Example

Let us look at the following implementation to check whether a matrix is diagonally dominant or not.

 Live Demo

#include <iostream>
const int N = 3;
using namespace std;
bool isDDM(int mat[N][N], int n){
   for (int i = 0; i < n; i++){
      int sum = 0;
      for (int j = 0; j < n; j++)
         sum += abs(mat[i][j]);
         sum -= abs(mat[i][i]);
         if (abs(mat[i][i]) < sum)
            return false;
   }
   return true;
}
int main(){
   int matSize = 3;
   int mat[N][N] = {
      { 3, -2, 1 },
      { 1, -3, 2 },
      { -1, 2, 4 }
   };
   if(isDDM(mat,matSize)){
      cout << "yes,its a diagonally dominant matrix";
   } else {
      cout << "NO, its not a diagonally dominant matrix";
   }
   return 0;
}

Output

The above code will produce the following output −

yes,its a diagonally dominant matrix

Updated on: 16-Jan-2021

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements