My problem is basically this:
I have a list, L, where each element is a matrix of the same dimension. I need to multiply each matrix inside this list by its corresponding element in an outside vector h, and then sum all the matrices.
set.seed(101)
L <- replicate(3, matrix(rnorm(4), 2), simplify = FALSE)
h <- 2:4
# I need this
L[[1]] * h[1] + L[[2]] * h[2] + L[[3]] * h[3]
Given that I need to experiment with a different number of matrices, and I have a bunch of them, I've got to do it in a smart way. My idea was
L1 <- lapply(L, function(x) x * h[x])
L2 <- Reduce('+', L1)
Where "h[x]" would be indexing the vector h by the index of the matrix x inside the list L, so I would get
L1 = list(L[[1]] * h[1], L[[2]] * h[2], L[[3]] * h[3])
So, the question is, how to I get the index of an element in a list by using the element itself? Something like h[L[[m1]]] to get h[1].
Or, if you got any other way of solving my problem, how do I do it?