tr: Calculate trace of various matrix products

Description Usage Arguments Value Author(s) Examples

Description

Calculate trace of various matrix products.

Usage

1
2
3
4
5
trA(A)
trAW(A,W)
trAWB(A,W,B)
trAWBW(A,W,B)
trAWBV(A,W,B,V)

Arguments

A,B

Square matrices represented as matrices or lists (see examples below).

W,V

Square matrices

Value

A number

Author(s)

S<f8>ren H<f8>jsgaard, sorenh@agrsci.dk

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
d <- 5
W <- matrix(rnorm(d*d),nr=d,nc=d); 
V <- W <- W+t(W)

## Turn list into matrix
##
tomat <- function(x){
  ans <- do.call("rbind", x)
  storage.mode(ans)<-"double"
  return(ans)
}

A1 <- tomat(list(c(1,2),c(1,3)))
A2 <- tomat(list(1,3,5))


## Just for checking the calculations
##
symMat <- function(A,d){
  ans <- matrix(0,nr=d,nc=d)
  for (i in 1:length(A)){
    e <- A[[i]]
    if (length(e)==1){
      ans[e,e] <- 1
    } else { 
      ans[e[1],e[2]] <-   ans[e[2],e[1]] <- 1 
    }
  }

  return(ans)
}

trAW(A1, W)
#sum(diag(symMat(A1,d=d) %*% W))

trAW(A2, W)
#sum(diag(symMat(A2,d=d) %*% W))

trAWB(A1, W, A2)
#sum(diag(symMat(A1,d=d) %*% W %*% symMat(A2,d=d)))

trAWBV(A1, W, A2, V)
#sum(diag(symMat(A1,d=d) %*% W %*% symMat(A2,d=d) %*% V))

gRc documentation built on May 2, 2019, 5:22 p.m.

Related to tr in gRc...