yrx1702
yrx1702

Reputation: 1641

Efficiently substract from matrix columnwise

I have a rather simple problem and was wondering whether some of you guys know a very efficient (=fast) solution for this:

I have two matrices mat and arr and want to accomplish the following: Take every column of arr and substract it from mat. Then take the logarithm of one minus the absolute value of the difference. That's it. Right now, I'm using sapply (see below), but I'm pretty sure that it's possible to do it faster (maybe using sweep?)

Code:

mat <- matrix(.3, nrow=10, ncol = 4)
arr <- matrix(.1, nrow=10, ncol = 10000)
i <- ncol(arr)
result <- sapply(1:i, function(ii) (log(1-abs(mat-arr[,ii]))))

Thanks for any ideas!

Upvotes: 2

Views: 36

Answers (1)

akrun
akrun

Reputation: 887128

We could replicate and then do a difference

result2 <- matrix(log(1- abs(rep(mat, ncol(arr)) - 
                      rep(arr, ncol(mat)))), ncol = i) 
identical(result, result2)
#[1] TRUE

Upvotes: 2

Related Questions