Reputation: 23
I don't know how to code this summation in R. As a beginner, I don't know how to code several loops in the same function.
The equation I need to code in R is
Upvotes: 2
Views: 428
Reputation: 6784
Taking josliber's example numbers, this can be done with simple matrix multiplication
alpha <- 1:3
sigma <- 2:4
rho <- cbind(c(1, .2, -.1), c(.2, 1, 0), c(-.1, 0, 1))
t(alpha * sigma) %*% rho %*% (alpha * sigma)
# [,1]
# [1,] 184
Upvotes: 3
Reputation: 44340
First you might want to make a matrix where element (i,j) is the i^th element of the alpha*sigma vector times the j^th element of that same vector. This can be accomplished with the outer
function in R:
alpha <- 1:3
sigma <- 2:4
outer(alpha*sigma, alpha*sigma)
# [,1] [,2] [,3]
# [1,] 4 12 24
# [2,] 12 36 72
# [3,] 24 72 144
The desired double summation is the sum of all elements in this multiplied element-wise with the matrix containing the rho_ij
values, which can be achieved in R with *
for element-wise multiplication and sum
for summing the element in a matrix:
(rho <- cbind(c(1, .2, -.1), c(.2, 1, 0), c(-.1, 0, 1)))
# [,1] [,2] [,3]
# [1,] 1.0 0.2 -0.1
# [2,] 0.2 1.0 0.0
# [3,] -0.1 0.0 1.0
sum(outer(alpha*sigma, alpha*sigma) * rho)
# [1] 184
Upvotes: 4