user3231352
user3231352

Reputation: 809

Multiply array with different dimension

I wanted to multiply(or divide) two arrays with different dimensions (a1=[48,38,31] and b1[48,38]). So far, I was using a for loop over the third dimension. However, I was wondering how to use (if it's possible) apply for that. Let's say I have the following samples:

a1<- array(rnorm(20), dim=c(2,3,3))
b1<- array(rnorm(20), dim=c(2,3))

If I tried to do directly a1/b1 (or *) I can't because they need to have the same dimensions. So I used a for loop:

for(i in 1:3){
  m1[,,i] <- a1[,,i]/b1
}

But I would like to avoid the use of the loop.

Upvotes: 3

Views: 730

Answers (2)

Patric
Patric

Reputation: 2131

Alternatively, you can use sweep function which is designed to do this kind of operation.

 a1<- array(rnorm(20), dim=c(2,3,3))
 b1<- array(rnorm(20), dim=c(2,3))

 m1 <- array(0, dim=c(2,3,3))

 # original solution
 for(i in 1:3){
    m1[,,i] <- a1[,,i]/b1
 }

 # apply sweep   
 # to avoid the warning info add 'check.margin=F'
 m2 <- sweep(a1, 1, b1, "/", check.margin=F)

 all.equal(m1, m2)
 #[1] TRUE

Upvotes: 1

akrun
akrun

Reputation: 887088

One option would be

array(c(a1)/rep(b1, dim(a1)[3]), dim= dim(a1))

Or we can use apply

apply(a1, 3, FUN=function(x) x/b1)

Upvotes: 2

Related Questions