Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply multidimensional array with same-sized matrix

Tags:

arrays

r

matrix

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!

like image 623
Alex Avatar asked Jan 28 '26 06:01

Alex


2 Answers

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)
like image 152
LyzandeR Avatar answered Jan 29 '26 22:01

LyzandeR


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

like image 24
Papples Avatar answered Jan 29 '26 22:01

Papples