Karl
Karl

Reputation: 67

Applying outer to columns within a matrix

I have two matrices: x

A B C
2 3 4
3 4 5

and y

D E
1 2
3 2

How can I subtract the combination of elements within columns? Giving me the following result:

AD AE BD BE CD CE
1  0  2  1  3  2
0  1  1  2  2  3

I have tried applying outer, but can't make it work with matrices. Would vectorizing a function be a solution? I have tried the code below, but it doesn't seem to work.

vecfun= Vectorize(fun)
fun=function(a,b)(a-b)
outer(x,y, vecfun)

Thanks in advance for any advice.

Upvotes: 1

Views: 194

Answers (2)

Arun
Arun

Reputation: 118799

Here's another way without loops/*apply family (assuming your matrices are x and y):

x[ , rep(seq_len(ncol(x)), each=ncol(y))] - y[, rep(seq_len(ncol(y)), ncol(x))]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0    2    1    3    2
[2,]    0    1    1    2    2    3

I'm not sure if it'll be faster, yet. But I thought it is an interesting approach. Also this would take twice the memory of your resulting matrix during computation.

Upvotes: 3

Thomas
Thomas

Reputation: 44525

This doesn't use outer, but gets your intended result:

> do.call(cbind,lapply(1:ncol(x),function(i) x[,i]-y))
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0    2    1    3    2
[2,]    0    1    1    2    2    3

Upvotes: 3

Related Questions