我有一个矩阵计算,需要使用R来计算。
答案 0 :(得分:2)
z <- matrix(1:9,nrow = 3,byrow = TRUE)
z
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
t(z)%*%z
[,1] [,2] [,3]
[1,] 66 78 90
[2,] 78 93 108
[3,] 90 108 126
答案 1 :(得分:0)
尝试一下:
z<-matrix(seq(1:9),ncol=3,nrow=3,byrow=TRUE)
A=z[1,]*t(z[1,])+z[2,]*t(z[2,])+z[3,]*t(z[3,])
A
# [,1] [,2] [,3]
# [1,] 66 93 126
Edit1:以下代码适用于任何尺寸,只要它是方形矩阵即可:
colSums(t(apply(z,1,function(x)(x[1:nrow(z)]*t(x[1:nrow(z)])))))
#[1] 66 93 126
Edit2:
t(z)%*%z #the following 3 lines will all give you the same thing!
crossprod(z)
matrix(colSums(t(apply(z,1,
function(x)(matrix(x[1:nrow(z)])%*% x[1:nrow(z)])))),ncol=nrow(z),byrow = TRUE)
# [,1] [,2] [,3]
#[1,] 66 78 90
#[2,] 78 93 108
#[3,] 90 108 126
答案 2 :(得分:0)
尝试一下(使用矩阵乘法):
library(optimbase)
Z <- matrix(1:9, byrow = TRUE, nrow = 3)
A <- transpose(Z[1, ]) %*% Z[1, ] + transpose(Z[2, ]) %*% Z[2, ] + transpose(Z[3, ]) %*% Z[3, ]
A # output
[,1] [,2] [,3]
[1,] 66 78 90
[2,] 78 93 108
[3,] 90 108 126
答案 3 :(得分:0)
尝试一下:
> z <- matrix(c(1,2,3,4,5,6,7,8,9), 3, byrow=TRUE)
> z
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> z[1,]
[1] 1 2 3
> matrix(z[1,])
[,1]
[1,] 1
[2,] 2
[3,] 3
矩阵乘法(列向量*行向量):
> matrix(z[1,]) %*% z[1,] + matrix(z[2,]) %*% z[2,] + matrix(z[3,]) %*% z[3,]
[,1] [,2] [,3]
[1,] 66 78 90
[2,] 78 93 108
[3,] 90 108 126
请参阅: http://www.philender.com/courses/multivariate/notes/matr.html
计算行向量*列向量时的结果不同:
> z[1,] %*% matrix(z[1,]) + z[2,] %*% matrix(z[2,]) + z[3,] %*% matrix(z[3,])
[,1]
[1,] 285