1

I am trying add a matrix to each 'sub-matrix' of a 3d array. I'd like to do this without a loop.

a = array(1:24, dim = 2:4)
a[1,,]
a[2,,]

b = array(1:12, dim = 3:4)
b

c1 = a[1,,] + b
c2 = a[2,,] + b

c = apply(a, 1, function(a_){
  da_ = dim(a_)
  db = dim(b)
  message(sprintf("The dimensions of a_ are [%i x %i] and the dimensions of b are [%i x %i]", da_[1], da_[2], db[1], db[2]))
  a_ + b
})

In the above code, I would like c[1,,] to be equal to c1, and c[2,,] to be equal to c2. Is this possible using the apply function?

PS: I found this similar question but no direct answer to the question was given.

markus
  • 25,843
  • 5
  • 39
  • 58
Chechy Levas
  • 2,206
  • 1
  • 13
  • 28

1 Answers1

1

Here is a way using rep:

d <- a + rep(b, each = dim(a)[1])
all.equal(d[1,,], c1)
# TRUE
markus
  • 25,843
  • 5
  • 39
  • 58