Posted on by Kalkicode
Code Matrix

Check if a matrix is symmetric

The problem at hand is to determine whether a given square matrix is symmetric or not. A matrix is considered symmetric if it is equal to its transpose. In other words, if matrix A is symmetric, then A[i][j] = A[j][i] for all valid indices i and j.

In simpler words, a symmetric matrix is a square matrix where the numbers above and below the diagonal are reflections of each other. So if you were to draw a line down the diagonal, the numbers on one side would be the same as the numbers on the other side but flipped.

Problem Statement

Given a square matrix of size SIZE x SIZE, we want to check whether the matrix is symmetric or not. The matrix's elements are integers, and we need to compare each element at position A[i][j] with the element at position A[j][i] for all valid indices i and j.

Example

Let's consider two matrices for demonstration:

Matrix A:

7  1  5  6
1  2  4  4
5  4  1  1
6  4  1  6

Matrix B:

1  2  3  6
2  5  4  4
5  4  1  1
6  4  1  6

For matrix A, the elements along the main diagonal and their transposed counterparts are equal, so it is symmetric. Hence, the output is "Yes".

For matrix B, there is at least one pair of elements that do not match their transposed counterparts, so it is not symmetric. Hence, the output is "No".

Solution Idea

To solve this problem, we can iterate through each element of the matrix and compare it with the corresponding element in the transposed position. If all corresponding elements are equal, then the matrix is symmetric; otherwise, it is not.

Pseudocode

is_symmetric(matrix):
    status = 1
    for i = 0 to SIZE:
        for j = 0 to SIZE:
            if matrix[i][j] != matrix[j][i]:
                status = 0
                break
    if status == 1:
        print "Yes"
    else:
        print "No"

Algorithm Explanation

  1. Start by defining a function is_symmetric(matrix) that takes the input matrix as its parameter.
  2. Initialize a variable status to 1. This variable will be used to track whether the matrix is symmetric or not.
  3. Use two nested loops to iterate through each element of the matrix. The outer loop iterates through rows, and the inner loop iterates through columns.
  4. Compare the element at position A[i][j] with the element at position A[j][i]. If they are not equal, set status to 0 and break out of the inner loop.
  5. After both loops complete, if status is still 1, then the matrix is symmetric. Print "Yes". Otherwise, print "No".

Code Solution

//C Program 
//Check if a matrix is symmetric
#include<stdio.h>

//indicating matrix size
#define SIZE 4 

//Display element of matrix
void show_data(int matrix[][SIZE])
{
  for (int i = 0; i < SIZE; ++i)
  {
    for (int j = 0; j < SIZE; ++j)
    {
      printf("%3d",matrix[i][j] );
    }
    printf("\n");
  }
  
}
//Check that if a given matrix is symmetric or not
void is_symmetric(int matrix[][SIZE])
{
  int status=1;

  for (int i = 0; i < SIZE && status == 1; ++i)
  {
    for (int j = 0; j < SIZE && status == 1; ++j)
    {
      //Compare matrix element
      if(matrix[i][j] != matrix[j][i])
      {
        status=0;
      }
    }
  }
  show_data(matrix);

  if(status==1)
  {
    printf("  Yes\n");
  }
  else
  {
    printf("  No\n");
  }
}
int main()
{
  //Matrix A
  int matrix1[][SIZE]= { 
    {7, 1, 5 ,6}, 
    { 1, 2, 4 ,4}, 
    { 5, 4, 1 ,1},
    { 6, 4, 1 ,6} 
  }; 
  
  is_symmetric(matrix1);
  
  //Matrix B
  int matrix2[][SIZE]= { 
    { 1, 2, 3 ,6}, 
    { 2, 5, 4 ,4}, 
    { 5, 4, 1 ,1},
    { 6, 4, 1 ,6} 
  };
  is_symmetric(matrix2); 
  
  return 0;
}


Output

  7  1  5  6
  1  2  4  4
  5  4  1  1
  6  4  1  6
  Yes
  1  2  3  6
  2  5  4  4
  5  4  1  1
  6  4  1  6
  No
/*
 C++ Program
 Check if a matrix is symmetric
*/
#include<iostream>
#define SIZE 4
using namespace std;

class MyMatrix {
  public:

    //Display element of matrix
    void show_data(int matrix[][SIZE], int row, int col) {
      for (int i = 0; i < row; ++i) {
        for (int j = 0; j < col; ++j) {
          cout << "  " << matrix[i][j];
        }
        cout << "\n";
      }
    }
  //Check that if a given matrix is symmetric or not
  void is_symmetric(int matrix[][SIZE]) {
    bool status = true;
    int row = SIZE;
    int col = row;
    for (int i = 0; i < row && status == true; ++i) {
      for (int j = 0; j < col && status == true; ++j) {
        //Compare matrix element

        if (matrix[i][j] != matrix[j][i]) {
          status = false;
        }
      }
    }
    this->show_data(matrix, row, col);
    if (status == true) {
      cout << "  Yes\n";
    } else {
      cout << "  No\n";
    }
  }
};
int main() {
  MyMatrix obj;
   //Matrix A
  int matrix1[][SIZE] = {
      {
        7,
        1,
        5,
        6
      },
      {
        1,
        2,
        4,
        4
      },
      {
        5,
        4,
        1,
        1
      },
      {
        6,
        4,
        1,
        6
      }
    };
  obj.is_symmetric(matrix1);
  //Matrix B
  int matrix2[][SIZE] = {
      {
        1,
        2,
        3,
        6
      },
      {
        2,
        5,
        4,
        4
      },
      {
        5,
        4,
        1,
        1
      },
      {
        6,
        4,
        1,
        6
      }
    };
  obj.is_symmetric(matrix2);
  return 0;
}

Output

  7  1  5  6
  1  2  4  4
  5  4  1  1
  6  4  1  6
  Yes
  1  2  3  6
  2  5  4  4
  5  4  1  1
  6  4  1  6
  No
/*
  Java Program
  Check if a matrix is symmetric
*/
public class MyMatrix {


  //Display element of matrix
  public void show_data(int [][]matrix,int row,int col)
  {
    for (int i = 0; i < row; ++i)
    {
      for (int j = 0; j < col; ++j)
      {
        System.out.print("  "+matrix[i][j] );
      }
      System.out.print("\n");
    }
    
  }
  //Check that if a given matrix is symmetric or not
  public void is_symmetric(int [][]matrix )
  {
    boolean status=true;

    int row = matrix.length;

    int col = matrix[0].length;

    if(row!=col)
    {
      status=false;
    }

    for (int i = 0; i < row && status == true; ++i)
    {
      for (int j = 0; j < col && status == true; ++j)
      {
        //Compare matrix element
        if(matrix[i][j] != matrix[j][i])
        {
          status=false;
        }
      }
    }
    show_data(matrix,row,col);

    if(status==true)
    {
      System.out.print("  Yes\n");
    }
    else
    {
      System.out.print("  No\n");
    }
  }

  public static void main(String[] args) {

    MyMatrix obj = new MyMatrix();

    //Matrix A
    int [][]matrix1= { 
      {7, 1, 5 ,6}, 
      { 1, 2, 4 ,4}, 
      { 5, 4, 1 ,1},
      { 6, 4, 1 ,6} 
    }; 
    
    obj.is_symmetric(matrix1);
    
    //Matrix B
    int [][]matrix2= { 
      { 1, 2, 3 ,6}, 
      { 2, 5, 4 ,4}, 
      { 5, 4, 1 ,1},
      { 6, 4, 1 ,6} 
    };
    obj.is_symmetric(matrix2); 
  }
}

Output

  7  1  5  6
  1  2  4  4
  5  4  1  1
  6  4  1  6
  Yes
  1  2  3  6
  2  5  4  4
  5  4  1  1
  6  4  1  6
  No
/*
  C# Program
  Check if a matrix is symmetric
*/
using System;
public class MyMatrix {


	//Display element of matrix
	public void show_data(int[,] matrix, int row, int col) {
		for (int i = 0; i < row; ++i) {
			for (int j = 0; j < col; ++j) {
				Console.Write("  " + matrix[i,j]);
			}
			Console.Write("\n");
		}

	}
	//Check that if a given matrix is symmetric or not
	public void is_symmetric(int[,] matrix) {
		Boolean status = true;

		int row = matrix.GetLength(0);

		int col = matrix.GetLength(1);

		if (row != col) {
			status = false;
		}

		for (int i = 0; i < row && status == true; ++i) {
			for (int j = 0; j < col && status == true; ++j) {
				//Compare matrix element
				if (matrix[i,j] != matrix[j,i]) {
					status = false;
				}
			}
		}
		show_data(matrix, row, col);

		if (status == true) {
			Console.Write("  Yes\n");
		} else {
			Console.Write("  No\n");
		}
	}

	public static void Main(String[] args) {

		MyMatrix obj = new MyMatrix();

		//Matrix A
		int[,] matrix1 = {
			{
				7,
				1,
				5,
				6
			},
			{
				1,
				2,
				4,
				4
			},
			{
				5,
				4,
				1,
				1
			},
			{
				6,
				4,
				1,
				6
			}
		};

		obj.is_symmetric(matrix1);

		//Matrix B
		int[,] matrix2 = {
			{
				1,
				2,
				3,
				6
			},
			{
				2,
				5,
				4,
				4
			},
			{
				5,
				4,
				1,
				1
			},
			{
				6,
				4,
				1,
				6
			}
		};
		obj.is_symmetric(matrix2);
	}
}

Output

  7  1  5  6
  1  2  4  4
  5  4  1  1
  6  4  1  6
  Yes
  1  2  3  6
  2  5  4  4
  5  4  1  1
  6  4  1  6
  No
<?php
/*
  Php Program
  Check if a matrix is symmetric
*/
class MyMatrix {
	//Display element of matrix

	public 	function show_data($matrix, $row, $col) {
		for ($i = 0; $i < $row; ++$i) {
			for ($j = 0; $j < $col; ++$j) {
				echo(" ". $matrix[$i][$j]);
			}
			echo("\n");
		}
	}
	//Check that if a given matrix is symmetric or not

	public 	function is_symmetric($matrix) {
		$status = true;
		$row = count($matrix);
		$col = count($matrix[0]);
		if ($row != $col) {
			$status = false;
		}
		for ($i = 0; $i < $row && $status == true; ++$i) {
			for ($j = 0; $j < $col && $status == true; ++$j) {
				//Compare matrix element

				if ($matrix[$i][$j] != $matrix[$j][$i]) {
					$status = false;
				}
			}
		}
		$this->show_data($matrix, $row, $col);
		if ($status == true) {
			echo(" Yes\n");
		} else {
			echo(" No\n");
		}
	}
};

function main() {
	$obj = new MyMatrix();
	//Matrix A
	$matrix1 = array(array(7, 1, 5, 6), array(1, 2, 4, 4), array(5, 4, 1, 1), array(6, 4, 1, 6));
	$obj->is_symmetric($matrix1);
	//Matrix B
	$matrix2 = array(array(1, 2, 3, 6), array(2, 5, 4, 4), array(5, 4, 1, 1), array(6, 4, 1, 6));
	$obj->is_symmetric($matrix2);
}
main();

Output

 7 1 5 6
 1 2 4 4
 5 4 1 1
 6 4 1 6
 Yes
 1 2 3 6
 2 5 4 4
 5 4 1 1
 6 4 1 6
 No
/*
 Node Js Program
 Check if a matrix is symmetric
*/
class MyMatrix {
	//Display element of matrix
	show_data(matrix, row, col) {
		for (var i = 0; i < row; ++i) {
			for (var j = 0; j < col; ++j) {
				process.stdout.write(" " + matrix[i][j]);
			}
			process.stdout.write("\n");
		}
	}
	//Check that if a given matrix is symmetric or not
	is_symmetric(matrix) {
		var status = true;
		var row = matrix.length;
		var col = matrix[0].length;
		if (row != col) {
			status = false;
		}
		for (var i = 0; i < row && status == true; ++i) {
			for (var j = 0; j < col && status == true; ++j) {
				//Compare matrix element

				if (matrix[i][j] != matrix[j][i]) {
					status = false;
				}
			}
		}
		this.show_data(matrix, row, col);
		if (status == true) {
			process.stdout.write(" Yes\n");
		} else {
			process.stdout.write(" No\n");
		}
	}
}

function main(args) {
	var obj = new MyMatrix();
	//Matrix A
	var matrix1 = [
		[7, 1, 5, 6],
		[1, 2, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	];
	obj.is_symmetric(matrix1);
	//Matrix B
	var matrix2 = [
		[1, 2, 3, 6],
		[2, 5, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	];
	obj.is_symmetric(matrix2);
}
main();

Output

 7 1 5 6
 1 2 4 4
 5 4 1 1
 6 4 1 6
 Yes
 1 2 3 6
 2 5 4 4
 5 4 1 1
 6 4 1 6
 No
# Python 3 Program
# Check if a matrix is symmetric
class MyMatrix :
  # Display element of matrix
  def show_data(self, matrix, row, col) :
    i = 0
    while (i < row) :
      j = 0
      while (j < col) :
        print(" ", matrix[i][j],end="")
        j += 1
      
      print(end="\n")
      i += 1
    
  
  # Check that if a given matrix is symmetric or not
  def is_symmetric(self, matrix) :
    status = True
    row = len(matrix)
    col = len(matrix[0])
    if (row != col) :
      status = False
    
    i = 0
    while (i < row and status == True) :
      j = 0
      while (j < col and status == True) :
        # Compare matrix element
        if (matrix[i][j] != matrix[j][i]) :
          status = False
        
        j += 1
      
      i += 1
    
    self.show_data(matrix, row, col)
    if (status == True) :
      print("  Yes")
    else :
      print("  No")
    
  

def main() :
  obj = MyMatrix()
  matrix1 = [
    [7, 1, 5, 6],
    [1, 2, 4, 4],
    [5, 4, 1, 1],
    [6, 4, 1, 6]
  ]
  obj.is_symmetric(matrix1)
  matrix2 = [
    [1, 2, 3, 6],
    [2, 5, 4, 4],
    [5, 4, 1, 1],
    [6, 4, 1, 6]
  ]
  obj.is_symmetric(matrix2)


if __name__ == "__main__":
  main()

Output

 7 1 5 6
 1 2 4 4
 5 4 1 1
 6 4 1 6
 Yes
 1 2 3 6
 2 5 4 4
 5 4 1 1
 6 4 1 6
 No
# Ruby Program 
# Check if a matrix is symmetric
class MyMatrix 
	# Display element of matrix
	def show_data(matrix, row, col) 
		i = 0
		while (i < row) 
			j = 0
			while (j < col) 
				print(" ", matrix[i][j])
				j += 1
			end
			print("\n")
			i += 1
		end
	end
	# Check that if a given matrix is symmetric or not
	def is_symmetric(matrix) 
		status = true
		row = matrix.length
		col = matrix[0].length
		if (row != col) 
			status = false
		end
		i = 0
		while (i < row and status == true) 
			j = 0
			while (j < col and status == true) 
				# Compare matrix element

				if (matrix[i][j] != matrix[j][i]) 
					status = false
				end
				j += 1
			end
			i += 1
		end
		self.show_data(matrix, row, col)
		if (status == true) 
			print(" Yes\n")
		else 
			print(" No\n")
		end
	end
end
def main() 
	obj = MyMatrix.new()
	matrix1 = [
		[7, 1, 5, 6],
		[1, 2, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	]
	obj.is_symmetric(matrix1)
	matrix2 = [
		[1, 2, 3, 6],
		[2, 5, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	]
	obj.is_symmetric(matrix2)
end
main()

Output

 7 1 5 6
 1 2 4 4
 5 4 1 1
 6 4 1 6
 Yes
 1 2 3 6
 2 5 4 4
 5 4 1 1
 6 4 1 6
 No
/*
 Scala Program
 Check if a matrix is symmetric
*/
class MyMatrix {
	//Display element of matrix
	def show_data(matrix: Array[Array[Int]], row: Int, col: Int): Unit = {
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				print(" " + matrix(i)(j));
				j += 1;
			}
			print("\n");
			i += 1;
		}
	}
	//Check that if a given matrix is symmetric or not
	def is_symmetric(matrix: Array[Array[Int]]): Unit = {
		var status: Boolean = true;
		var row: Int = matrix.length;
		var col: Int = matrix(0).length;
		if (row != col) {
			status = false;
		}
		var i: Int = 0;
		while (i < row && status == true) {
			var j: Int = 0;
			while (j < col && status == true) {
				//Compare matrix element

				if (matrix(i)(j) != matrix(j)(i)) {
					status = false;
				}
				j += 1;
			}
			i += 1;
		}
		this.show_data(matrix, row, col);
		if (status == true) {
			print(" Yes\n");
		} else {
			print(" No\n");
		}
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		var obj: MyMatrix = new MyMatrix();
		var matrix1: Array[Array[Int]] = Array(
			Array(7, 1, 5, 6),
			Array(1, 2, 4, 4),
			Array(5, 4, 1, 1),
			Array(6, 4, 1, 6));
  		obj.is_symmetric(matrix1);
		var matrix2: Array[Array[Int]] = Array(
			Array(1, 2, 3, 6),
			Array(2, 5, 4, 4),
			Array(5, 4, 1, 1),
			Array(6, 4, 1, 6));
  		obj.is_symmetric(matrix2);
	}
}

Output

 7 1 5 6
 1 2 4 4
 5 4 1 1
 6 4 1 6
 Yes
 1 2 3 6
 2 5 4 4
 5 4 1 1
 6 4 1 6
 No
/*
  Swift 4 Program
  Check if a matrix is symmetric
*/
class MyMatrix {
	//Display element of matrix
	func show_data(_ matrix: [[Int]], _ row: Int, _ col: Int) {
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				print(" ", matrix[i][j],terminator:"");
				j += 1;
			}
			print(terminator:"\n");
			i += 1;
		}
	}
	//Check that if a given matrix is symmetric or not
	func is_symmetric(_ matrix: [[Int]]) {
		var status: Bool = true;
		let row: Int = matrix.count;
		let col: Int = matrix[0].count;
		if (row != col) {
			status = false;
		}
		var i: Int = 0;
		while (i < row && status == true) {
			var j: Int = 0;
			while (j < col && status == true) {
				//Compare matrix element

				if (matrix[i][j] != matrix[j][i]) {
					status = false;
				}
				j += 1;
			}
			i += 1;
		}
		self.show_data(matrix, row, col);
		if (status == true) {
			print("  Yes\n");
		} else {
			print("  No\n");
		}
	}
}
func main() {
	let obj: MyMatrix = MyMatrix();
	let matrix1: [[Int]] = [
		[7, 1, 5, 6],
		[1, 2, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	];
	obj.is_symmetric(matrix1);
	let matrix2: [[Int]] = [
		[1, 2, 3, 6],
		[2, 5, 4, 4],
		[5, 4, 1, 1],
		[6, 4, 1, 6]
	];
	obj.is_symmetric(matrix2);
}
main();

Output

  7  1  5  6
  1  2  4  4
  5  4  1  1
  6  4  1  6
  Yes

  1  2  3  6
  2  5  4  4
  5  4  1  1
  6  4  1  6
  No

Time Complexity

The time complexity of this algorithm is O(SIZE^2), where SIZE is the dimension of the square matrix. This is because we are iterating through each element of the matrix exactly once in a nested loop structure.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment