broccoli
broccoli

Reputation: 4846

R multiply matrices: but with a special function

I have two square matrices A and B. Both have either 1 or 0 in each of their entries. An example shown below

A
channel
 id a b c
  1 1 1 1
  2 1 0 1
  3 1 0 0

B
       id
channel 1 2 3
  a     1 1 1
  b     1 0 0
  c     1 1 0

I want to multiply them. However, at the time when each element of A%*%B is computed I do not want the sum, instead I want to OR each element and then take the resulting sum. For example to compute the element at row=2 and column=3, a typical matrix multiplication would do (1*1 + 0*1 + 0*0) = 1, instead I want to do (1|1) + (0|1) + (0|0) = 2. How would I do this? apply? plyr? thanks much in advance.

Upvotes: 3

Views: 133

Answers (1)

IRTFM
IRTFM

Reputation: 263381

 A <-scan()
1:   1 1 1
4:   1 0 1
7:   1 0 0
10: 
Read 9 items
 B<-scan()
1:        1 1 1
4:        1 0 0
7:        1 1 0
10: 
Read 9 items

 A<-matrix(A, 3, byrow=TRUE)
 B<-matrix(B, 3, byrow=TRUE)

Logical OR with 0/1 is same as pmax:

pm <-  function(x,y) sum(pmax(A[x,],B[,y])) 
outer(1:3, 1:3, Vectorize(pm) )

     [,1] [,2] [,3]
[1,]    3    3    3
[2,]    3    2    2
[3,]    3    2    1

Upvotes: 3

Related Questions