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

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 for subtracting B from each matrix of array A will be:

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

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

+6
source share
3 answers

This is for sweep .

 sweep(A, 1:2, B) 
+8
source

Perhaps not very intuitive:

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

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

 d <- A - as.vector(B) 

and it will be much faster. This is the same idea as when subtracting a vector from the matrix: the vector is processed, so it is subtracted for each column.

+4
source

Source: https://habr.com/ru/post/948155/


All Articles