📜  身份矩阵的Python程序

📅  最后修改于: 2022-05-13 01:55:30.431000             🧑  作者: Mango

身份矩阵的Python程序

身份矩阵简介:

单位矩阵的字典定义是一个方阵,其中主对角线或主对角线的所有元素都是 1,所有其他元素都是零。在下图中,每个矩阵都是一个单位矩阵。

在线性代数中,这有时被称为单位矩阵,它是一个方阵(大小 = nxn),主对角线上为 1,其他地方为 0。单位矩阵用“ I ”表示。有时 U 或 E 也用于表示单位矩阵。
单位矩阵的一个属性是,如果它与单位矩阵相乘,它会使矩阵保持不变。

例子:

Input  : 2
Output : 1 0
         0 1

Input :  4
Output : 1 0 0 0
         0 1 0 0
         0 0 1 0
         0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as 
1 and everything else as 0.

打印身份矩阵的程序:
逻辑很简单。您需要在行等于矩阵列的位置打印 1 并将所有其他位置设为 0。

Python3
# Python code to print identity matrix
  
# Function to print identity matrix
def Identity(size):
    for row in range(0, size):
        for col in range(0, size):
  
            # Here end is used to stay in same line
            if (row == col):
                print("1 ", end=" ")
            else:
                print("0 ", end=" ")
        print()
  
# Driver Code        
size = 5
Identity(size)


Python3
# Python3 program to check 
# if a given matrix is identity
MAX = 100;
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;
  
# Driver Code
N = 4;
mat = [[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]]; 
if (isIdentity(mat, N)):
    print("Yes ");
else:
    print("No ");
  
# This code is contributed
# by mits


输出:

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  


检查给定方阵是否为单位矩阵的程序:

Python3

# Python3 program to check 
# if a given matrix is identity
MAX = 100;
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;
  
# Driver Code
N = 4;
mat = [[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]]; 
if (isIdentity(mat, N)):
    print("Yes ");
else:
    print("No ");
  
# This code is contributed
# by mits

输出:

Yes