Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply array with different dimension

Tags:

r

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.

like image 541
user3231352 Avatar asked Jul 08 '26 13:07

user3231352


2 Answers

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)
like image 75
akrun Avatar answered Jul 11 '26 05:07

akrun


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
like image 42
Patric Avatar answered Jul 11 '26 05:07

Patric