Unexpected result of matrix multiplication in R

R program does not return the expected matrix multiplication

    a<- c(0,1,1,0)
    A<- matrix(a,2,2)
    B<- matrix(c(1,2,3,4),2,2,byrow=TRUE)
    A*B

gives final answer as matrix(c(0,2,3,0), ncol = 2, byrow=TRUE):

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

but the actual answer should be matrix(c(3,4,1,2), ncol = 2, byrow=TRUE)

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

Upvotes: 0

Views: 187

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

You can use either %*% or crossprod for matrix multiplication

> A %*% B
     [,1] [,2]
[1,]    3    4
[2,]    1    2

> crossprod(A, B)
     [,1] [,2]
[1,]    3    4
[2,]    1    2 

Note that the result is a 2x2 matrix, if you want a vector as in your example, then use matrix(crossprod(A, B), ncol=1)

Upvotes: 2

Related Questions