Search code examples
rmatrix-multiplication

Matrix Multiplication "*" works in MATLAB but not in R


I'm trying to multiply a 5 x 3 matrix X by its transpose tX in R.

> X
     [,1] [,2] [,3]
[1,]    1   13  0.5
[2,]    1   23  0.4
[3,]    1    7 -0.2
[4,]    1   16  1.0
[5,]    1   11  0.3

> tX
     [,1] [,2] [,3] [,4] [,5]
[1,]  1.0  1.0  1.0    1  1.0
[2,] 13.0 23.0  7.0   16 11.0
[3,]  0.5  0.4 -0.2    1  0.3

> tX * X
Error in tX * X: array incompatibili

I did this in MATLAB and got immediately the right result. Why can't I do this in R? Thank You.

compute this in MATLAB


Solution

  • You need tX %*% X. Or try crossprod(X). See ?"%*%".

    Actually, if you just read the info, you will see this. I added it in two days ago.

    The "*" is used for Hadamard product, i.e., the element-wise product. Since tX and X don't have the same dimension, you get error. (A hint: I don't know how you get tX. In R, function t transposes a matrix. See info.)


    I haven't used MATLAB for 10 years. The following docs for R2018a looks different from what I recall.

    Anyway, the syntax between two scientific languages are different enough.