📜  Python程序查找矩阵的转置

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

Python程序查找矩阵的转置

矩阵的转置是通过将行更改为列和将列更改为行来获得的。换言之,A[][] 的转置是通过将 A[i][j] 更改为 A[j][i] 来获得的。

矩阵转置

对于方阵:

下面的程序找到 A[][] 的转置并将结果存储在 B[][] 中,我们可以将 N 更改为不同的维度。

# Python3 Program to find
# transpose of a matrix
  
N = 4
   
# This function stores
# transpose of A[][] in B[][]
  
def transpose(A,B):
  
    for i in range(N):
        for j in range(N):
            B[i][j] = A[j][i]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]]
   
   
B = A[:][:] # To store result
  
transpose(A, B)
   
print("Result matrix is")
for i in range(N):
    for j in range(N):
        print(B[i][j], " ", end='')
    print()
      
# This code is contributed by Anant Agarwal.
输出:
Result matrix is
1  2  3  4  
2  2  3  4  
3  3  3  4  
4  4  4  4

对于矩形矩阵:

下面的程序找到 A[][] 的转置并将结果存储在 B[][] 中。

# Python3 Program to find
# transpose of a matrix
  
M = 3
N = 4
  
# This function stores
# transpose of A[][] in B[][]
  
def transpose(A, B):
  
    for i in range(N):
        for j in range(M):
            B[i][j] = A[j][i]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3]]
  
  
# To store result
B = [[0 for x in range(M)] for y in range(N)] 
  
transpose(A, B)
  
print("Result matrix is")
for i in range(N):
    for j in range(M):
        print(B[i][j], " ", end='')
    print()    
输出:
Result matrix is
1  2  3  
1  2  3  
1  2  3  
1  2  3

就地矩阵:

# Python3 Program to find
# transpose of a matrix
  
N = 4
   
# Finds transpose of A[][] in-place
def transpose(A):
  
    for i in range(N):
        for j in range(i+1, N):
            A[i][j], A[j][i] = A[j][i], A[i][j]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]]
   
transpose(A)
   
print("Modified matrix is")
for i in range(N):
    for j in range(N):
        print(A[i][j], " ", end='')
    print()
      
# This code is contributed by Anant Agarwal.
输出:
Modified matrix is
1  2  3  4  
1  2  3  4  
1  2  3  4  
1  2  3  4

请参阅有关程序的完整文章以查找矩阵的转置以获取更多详细信息!