I'd like to multiply each matrix (13x10) of an array (13x10x10) dfarray = array((1),dim=c(13,10,10)) with another matrix of the same size (13x10) mat=matrix(2,13,10).
I tried the approach posted here, but after dfarray1 <- mat %*% dfarray (after changing the dimensions as described in the post mentioned) the length changes (1300 vs. 1000) as well as the dimensions of my array.
I feel like I'm on the right track but somehow the last bit is missing.
Any help would be much appreciated!
Try this in order to do element-wise matrix multiplication.
#initiate new array with above dimensions
newarray <- array(1, dim=c(13,10,10))
#populate each matrix of the array
for (i in 1:10){
newarray[, , i] <- dfarray[, , i] * mat
}
Output:
> dim(newarray)
[1] 13 10 10
Or as an alternative way as per @DavidArenburg 's comment just:
newarray[] <- apply(dfarray, 3, `*`, mat)
sweep also comes to the rescue here. For a one line alternative without initialisation you can do:
newarray <- sweep(x=dfarray, MARGIN=c(1, 2), STATS=mat, FUN='*')
According to the documentation, this will multiply dfarray by mat in the first and second dimensions.
You can even set check.margin = TRUE to check your array size and speed up execution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With