Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract matrix of n,k dimensions from array of matrices of 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 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?

like image 476
Newbie_R Avatar asked Jun 26 '13 16:06

Newbie_R


3 Answers

This is what sweep is for.

sweep(A, 1:2, B)
like image 82
Matthew Plourde Avatar answered Oct 23 '22 16:10

Matthew Plourde


Maybe not very intuitive:

A[] <- apply(A, 3, `-`, B)
like image 43
Hong Ooi Avatar answered Oct 23 '22 15:10

Hong Ooi


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.

like image 4
flodel Avatar answered Oct 23 '22 15:10

flodel