📜  如何在忽略 R 中的缺失值的同时将矩阵乘以其转置?

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

如何在忽略 R 中的缺失值的同时将矩阵乘以其转置?

在本文中,我们将讨论如何在 R 编程语言中忽略缺失值的情况下将矩阵乘以其转置。可以通过将矩阵中的所有 NA 替换为 0 来完成

值的替换可以在 O(n*m) 中执行,其中 n 是行数,m 是列数。替换为 0 不会影响乘积,因此,这是一个有效的解决方案。然后可以使用 t(matrix) 计算转置。乘积可以通过 R 中的以下语法计算:

m1 %*% m2 , where m1 and m2 are the matrices involved. 

如果 m1 是 n*m 维的矩阵,m2 是 m*n 的矩阵(因为它是转置),则获得的乘积矩阵是 n * n 的方阵。

示例 1:

R
# declaring matrix 
mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2)
  
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
  
# printing original matrix
print ("Original Matrix")
print (mat)
  
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
  
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)


R
# declaring matrix 
mat = matrix(c(10, NA, 7), ncol = 3)
  
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
  
# printing original matrix
print ("Original Matrix")
print (mat)
  
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
  
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)


输出:

[1] "Original Matrix"
    [,1] [,2]
[1,]    1    3
[2,]    0    0
[3,]    2    4
[1] "Transpose Matrix"
    [,1] [,2] [,3]
[1,]    1    0    2
[2,]    3    0    4
[1] "Product Matrix"
    [,1] [,2] [,3]
[1,]   10    0   14
[2,]    0    0    0
[3,]   14    0   20

原始矩阵的维度为 3 x 2,转置的维度为 2×3。将缺失值替换为 0 并将这两个值相乘,我们得到等效于 3×3 方阵的乘积矩阵。

示例 2:原始矩阵的维度为 1 x 3,转置的维度为 3×1。将缺失值替换为 0 并将这两个值相乘,我们得到等效于 1×1 方阵的乘积矩阵,它基本上是一个奇异单元矩阵。

电阻

# declaring matrix 
mat = matrix(c(10, NA, 7), ncol = 3)
  
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
  
# printing original matrix
print ("Original Matrix")
print (mat)
  
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
  
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)

输出

[1] "Original Matrix"
    [,1] [,2] [,3]
[1,]   10   0    7
[1] "Transpose Matrix"
    [,1]
[1,]   10
[2,]    0
[3,]    7
[1] "Product Matrix"
    [,1]
[1,]   149