Search code examples
rmatrixmultiplicationdimensions

Multiplication of matrices in R - problem of dimensions


I am trying to multiply to matrices in R:

I know this multiplication can be done, but I am getting an error. Any idea why?

> d1
     [,1]
[1,]   -3
[2,]    0
[3,]    3

> t1
     [,1] [,2] [,3]
[1,]    2    2    2

> t1 * d1
Error in t1 * d1 : non-conformable arrays

Solution

  • A few details more starting from @ThomasIsCoding comment:

    d1<-as.matrix(c(-3,0,3))
    t1<-t(as.matrix(c(2,2,2)))
    
    
    d1 %*% t1
         [,1] [,2] [,3]
    [1,]   -6   -6   -6
    [2,]    0    0    0
    [3,]    6    6    6
    

    From the official CRAN documentation about matrix multiplication

    A * B is the matrix of element by element products and

    A %*% B is the matrix product.

    If x is a vector, then

    x %% A %% x is a quadratic form.

    Link to the documenation HERE.