Subtract matrix of n,k dimensions from array of matrices of n,k dimensions

有些话、适合烂在心里 提交于 2019-12-12 10:39:25

问题


If I have an array A

A <- array(0, c(4, 3, 5))
for(i in 1:5) {
  set.seed(i)
  A[, , i] <- matrix(rnorm(12), 4, 3)
}

and if I have matrix B

set.seed(6)
B <- matrix(rnorm(12), 4, 3)

The code to subtract B from the each matrix of the array A would be:

d<-array(0, c(4,3,5))
for(i in 1:5){
  d[,,i]<-A[,,i]-B
}

However, what would be the code to perform the same calculation using a function from "apply" family?


回答1:


This is what sweep is for.

sweep(A, 1:2, B)



回答2:


Maybe not very intuitive:

A[] <- apply(A, 3, `-`, B)



回答3:


Because you are looping on the last array dimension, you can simply do:

d <- A - as.vector(B)

and it will be much faster. It is the same idea as when you subtract a vector from a matrix: the vector is recycled so it is subtracted to each column.



来源:https://stackoverflow.com/questions/17325881/subtract-matrix-of-n-k-dimensions-from-array-of-matrices-of-n-k-dimensions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!