Home > Software engineering >  I want to multiply each value in the vector a with each matrix in the array? How can I do this?
I want to multiply each value in the vector a with each matrix in the array? How can I do this?

Time:09-19

The array-function in c gives me 3 matrices in the array. I want to multiply each value in vector a with each matrix from c.

When I run this code, it seems that values are calculated in the wrong order. Some help will be much appreciated.

N <- c("P1", "P2", "D1", "D2")

a = matrix(c(16.2, 18, 21), ncol = 3)

b <- matrix(c(
  0,  2721, 3109, 1943,
  2721, 0, 1166, 1943,
  3109, 1166, 0, 1166,
  1943, 1943, 1166,0
), ncol = 4, dimnames = list(N, N))

c <- array(c(b), dim = c(4,4,3))[,,c(1:3)]* a[c(1:3)]

CodePudding user response:

I think this is what you want:

a <- array(rep(a, each=16), dim=c(4, 4, 3))  # Make array of a
c <- array(rep(b, 3), dim = c(4, 4, 3), dimnames=list(N, N))
d <- a * c
d
# , , 1
# 
#         P1      P2      D1      D2
# P1     0.0 44080.2 50365.8 31476.6
# P2 44080.2     0.0 18889.2 31476.6
# D1 50365.8 18889.2     0.0 18889.2
# D2 31476.6 31476.6 18889.2     0.0
# 
# , , 2
# 
#       P1    P2    D1    D2
# P1     0 48978 55962 34974
# P2 48978     0 20988 34974
# D1 55962 20988     0 20988
# D2 34974 34974 20988     0
# 
# , , 3
# 
#       P1    P2    D1    D2
# P1     0 57141 65289 40803
# P2 57141     0 24486 40803
# D1 65289 24486     0 24486
# D2 40803 40803 24486     0

If you are willing to get the answer as a list:

a <- c(16.2, 18, 21)
d <- lapply(a, "*", b)   # Three matrix list
library(abind)
d2 <- abind(d, along=3)  # Convert list to array
  •  Tags:  
  • r
  • Related