Question: Program to check whether the matrix is Identity or not.
A matrix is Said to be identity matrix if it satisfied following criteria:
Identity Matrix :
We denote the identity matrix of order n. When order is clear by context, we simply write it as I.
For example:
In the above A, B, C are Identity matrix of order 1, 2, 3 respectively.
Observe that Scalar Matrix is an identity matrix when k = 1. But every Identity matrix is clearly a scalar matrix.
Code Snippet:
Read Also:
Types of matrix in C#
A matrix is Said to be identity matrix if it satisfied following criteria:
- Matrix is Square matrix
- Element of diagonal are all 1.
- Rest element of matrix excluding diagonal are all zero.
Identity Matrix :
We denote the identity matrix of order n. When order is clear by context, we simply write it as I.
For example:
Observe that Scalar Matrix is an identity matrix when k = 1. But every Identity matrix is clearly a scalar matrix.
Code Snippet:
- using System;
- public class IdtMat
- {
- public static void Main()
- {
- int i, row, col;
- Console.Write("\nEnter the no. of rows and cols : ");
- i = Convert.ToInt32(Console.ReadLine());
- int[,] matA = new int[i, i];
- Console.WriteLine("\nEnter the Elements in Matrix:\n");
- for(row = 0; row < i; row++)
- {
- for(col = 0; col < i; col++)
- {
- Console.Write("A[{0}, {1}] = ", row, col);
- matA[row,col]= Convert.ToInt32(Console.ReadLine());
- }
- Console.WriteLine();
- }
- Console.WriteLine("Matrix A:\n");
- for(row = 0; row < i; row++)
- {
- for(col = 0; col < i; col++)
- Console.Write("{0, 2} ", matA[row,col]);
- Console.WriteLine();
- }
- bool isIdentity = true;
- for(row = 0; row < i; row++)
- {
- for(col = 0; col < i; col++)
- {
- if ((row == col && matA[row, col] != 1) ||
- (row != col && matA[row, col] != 0))
- {
- isIdentity = false;
- break;
- }
- }
- }
- if(isIdentity)
- {
- Console.WriteLine("\nIdentity Matrix");
- }
- else
- {
- Console.WriteLine("\nNot an Identity Matrix");
- }
- Console.ReadKey(true);
- }
- }
** Complete code
Description:
In the above code first of all we declare some variable row, col, i to read and write the matrix we take a 2-dimensional array of matA and a bool variable which is initialize to true.
First of all we enter the no. of row and column in Line 9,10,11 . After that we enter the element of matrix and print the matrix.
- for(row = 0; row < i; row++)
- {
- for(col = 0; col < i; col++)
- {
- if ((row == col && matA[row, col] != 1) ||
- (row != col && matA[row, col] != 0))
- {
- isIdentity = false;
- break;
- }
- }
- }
In the above piece of code we design the logic of Identity matrix if i and j equal to each other i.e (1,1) (2,2) (3,3) then "1" is print or if i and j not equals to each other and if elements of matrix not equals to 0 than ths IsIdentity bool value changed to false.
Screenshot of output:
Read Also:
Types of matrix in C#