📜  R中的矩阵转置

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

R中的矩阵转置

矩阵的转置是一种操作,其中我们将矩阵的行转换为列,将矩阵的列转换为行。执行矩阵转置的一般方程如下。

Aij = Aji  where i is not equal to j

例子:

Matrix M ---> [1, 8, 9
               12, 6, 2
               19, 42, 3]

Transpose of M
Output --->   [1, 12, 19
               8, 6, 42,
               9, 2, 3]

矩阵的转置可以通过两种方式执行:

  • 使用 t()函数查找转置
Python3
# R program for Transpose of a Matrix
 
# create a matrix with 2 rows
# using matrix() method
M <- matrix(1:6, nrow = 2)
 
# print the original matrix
print(M)
 
# transpose of matrix
# using t() function.
t <- t(M)
 
# print the transpose matrix
print(t)


Python3
# create matrix with 3 rows and 3 columns
Matrix = matrix(1:9, nrow = 3)
 
# print the matrix
print(Matrix)
 
# create another matrix
M2 = Matrix
 
# Loops for Matrix Transpose
for (i in 1:nrow(M2))
{
    # iterate over each row
    for (j in 1:ncol(M2))
    {
        # iterate over each column
        # assign the correspondent elements
        # from row to column and column to row.
        M2[i, j] <- Matrix[j, i]
    }
}
 
# print the transposed matrix
print(M2)


  • 输出:
[, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6

     [, 1] [, 2]
[1, ]    1    2
[2, ]    3    4
[3, ]    5    6
  • 通过使用循环遍历每个值:

Python3

# create matrix with 3 rows and 3 columns
Matrix = matrix(1:9, nrow = 3)
 
# print the matrix
print(Matrix)
 
# create another matrix
M2 = Matrix
 
# Loops for Matrix Transpose
for (i in 1:nrow(M2))
{
    # iterate over each row
    for (j in 1:ncol(M2))
    {
        # iterate over each column
        # assign the correspondent elements
        # from row to column and column to row.
        M2[i, j] <- Matrix[j, i]
    }
}
 
# print the transposed matrix
print(M2)
  • 输出:
[,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9