【问题标题】:How to add a 2d matrix to a 3d array and preserve the shape of the 3d arrray?如何将 2d 矩阵添加到 3d 数组并保留 3d 数组的形状?
【发布时间】:2020-06-13 21:50:31
【问题描述】:

我正在尝试向 3d 数组的每个“子矩阵”添加一个矩阵。我想在没有循环的情况下执行此操作。

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
})

在上面的代码中,我希望c[1,,] 等于c1,并且c[2,,] 等于c2。 这可以使用apply 函数吗?

PS:我找到了this similar question,但没有直接回答这个问题。

【问题讨论】:

    标签: r arrays matrix multidimensional-array


    【解决方案1】:

    这是使用rep的一种方式:

    d <- a + rep(b, each = dim(a)[1])
    all.equal(d[1,,], c1)
    # TRUE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多