Identity matrix: A square matrix in which all the diagonal elements are 1’s and all the remaining elements in that matrix are 0’s. Then that square matrix is called an Identity matrix.
#Identity matrix of the required size using for loops.
N=int(input("Enter a number: "))
for x in range(0,N):
for y in range(0,N):
if(x==y):
print("1"," ",end=" ")
else:
print("0"," ",end=" ")
print( )
Output
Enter a number: 3
1 0 0
0 1 0
0 0 1
Enter a number: 5
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
# To print identity matrix using functions.
def iden_mat(size):
for row in range(0, size):
for col in range(0, size):
if (row == col):
print("1 ", end=" ")
else:
print("0 ", end=" ")
print( )
size = 4
iden_mat(size)
Output
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
#To check whether the given matrix is an identity.
def isIdentity(mat, N):
for row in range(N):
for col in range(N):
if (row == col and
mat[row][col] != 1):
return False;
elif (row != col and
mat[row][col] != 0):
return False;
return True;
N = 4;
mat = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]];
if (isIdentity(mat, N)):
print("It is an identity matrix ");
else:
print("No, It is not an Identity matrix ");
Output
Yes, It is an identity matrix
#A dict of tuples of two ints (x, y) are used to represent the matrix.
def iden_mat(size):
return {(x, y):int(x == y) for x in range(size) for y in range(size)}
size = 5
matrix = iden_mat(size)
print('\n'.join(' '.join(str(matrix[(x, y)]) for x in range(size)) for y in range(size)))