你可以這樣做:
sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3)
x <- t(matrix(rep(1:3, 10),3,10))
mynorm <- function(x, sig) t(x) %*% sig %*% x
apply(x, 1, mynorm, sig=sigma)
這裏是tcrossprod()
變體:
mynorm <- function(x, sig) tcrossprod(x, sig) %*% x
apply(x, 1, mynorm, sig=sigma)
這裏是基準(包括來自compute only diagonals of matrix multiplication in R的解決方案變體,感謝@Benjamin的鏈接):
mynorm1 <- function(x, sig) t(x) %*% sig %*% x
mynorm2 <- function(x, sig) tcrossprod(x, sig) %*% x
microbenchmark(n1=apply(x, 1, mynorm1, sig=sigma),
n2=apply(x, 1, mynorm2, sig=sigma),
n3 = colSums(t(x) * (sigma %*% t(x))),
n4 = rowSums(x * t(sigma %*% t(x))),
n5 = rowSums(x * (x %*% t(sigma))),
n6 = rowSums(x * tcrossprod(x, sigma)),
Eugen1 = diag(x %*% sigma %*% t(x)),
Eugen2 = diag(x %*% tcrossprod(sigma, x)),
unit="relative")
這給了我 「錯誤的T(X)%*%西格瑪:是非柔順的論點」 –
好吧,那麼x%*%西格瑪%*%T( X)。它爲我工作。 – EugenR
@EugenR您正在計算不需要的元素。 – jogo