3

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!

1
  • Have you heard of tensorA package? Commented Jun 8, 2016 at 0:54

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

11 Comments

Or just newarray[] <- apply(dfarray, 3, `%*%`, mat)
@DavidArenburg Yeah this one is good too. I find that using a for-loop is easier for someone to understand the concept. Do you want me to add to my answer or do you want to post as a new one? In terms of speed it should be the same I suppose (or the for-loop slightly faster) since apply is base-R.
I guess you can edit your answer, as I'm not entirely sure that this is what OP after.
Thanks for your quick reply, I just realised that I wrote my question the "wrong" way around. I meant multiplying an array (13x10x10) with a matrix of 13x10. Sorry, edited my question earlier but somehow didn't get through.
@Alex Your mat is of 10x13 dimensions (and not 13x10). The array is of 13x10x10. The result of multiplying the two will be an array of 13x13x10. My answer does exactly that.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.