2017-10-20 119 views
0

我具有由基質sigmavectoriced範數/矩陣乘法

sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3)) 

描述爲了計算向量的範數我計算

t(x) %*% sigma %*% x 

這對於一個矢量例如正常工作範數x = 1:3

但是我想計算許多載體的規範,同時,這也是我有

x <- t(matrix(rep(1:3, 10),3,10)) 

(當然充滿了不同的條目)。

有沒有辦法同時計算每個向量的範數? 也就是說像

lapply(1:10, function(i) t(x[i,]) %*% sigma %*% x[i,]) 

回答

3

你可以這樣做:

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") 
2

你怎麼看待這個簡單的矩陣乘法什麼:

diag(t(x) %*% sigma %*% x) 

編輯:矩陣乘法後,你所需要的對角線(當然)。

然後它更快然後用解決方案適用

+0

這給了我 「錯誤的T(X)%*%西格瑪:是非柔順的論點」 –

+0

好吧,那麼x%*%西格瑪%*%T( X)。它爲我工作。 – EugenR

+0

@EugenR您正在計算不需要的元素。 – jogo

2

這應該做

> sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3) 
> x <- t(matrix(rep(1:30, 10),3,10)) 
> 
> # should give 
> t(x[1, ]) %*% sigma %*% x[1, ] 
    [,1] 
[1,] 16 
> t(x[2, ]) %*% sigma %*% x[2, ] 
    [,1] 
[1,] 97 
> 
> # which you can get by 
> rowSums((x %*% sigma) * x) 
[1] 16 97 250 475 772 1141 1582 2095 2680 3337 
+1

這個問題很接近於https://stackoverflow.com/q/21708489/5861244 –