Allow "hidden" scalar multiplication in R


I am translating a code from Matlab to R. In Matlab, one of the code line is


where B is a matrix and A is either a matrix or a scalar (for example, A=1) depending on certain conditions. And this works perfectly well since matrix*matrix or scalar *matrix is written the same way in Matlab (up to appropriate dimensions for matrix multiplications, which is the case).

However, in R, things become a bit more complicated. This becomes

C=A %*% B

which works fine… unless A is a scalar. Indeed, just writing

1 %*% diag(5)


non-conformable arguments

while in Matlab, such a problem does not even exist.

Is there a way to translate my Matlab instruction C=A*B in R while still keeping the flexibility I need, as described above ?

Note, that setting A to the identity matrix wouldn’t be satisfying: sometimes A is a scalar and cannot be changed into a matrix. I really need the "raw" flexibility described above

>Solution :

You can create your own infix operator to deal with this issue. tryCatch is a way to deal with errors. If %*% returns an error, then the function will execute x * y:

`%m%` <- function(x, y) tryCatch(x %*% y, error = function(e) x * y)


2 %m% diag(6)
     [,1] [,2]
[1,]    2    0
[2,]    0    2

matrix(1:4, nrow = 2) %m% matrix(4:1, nrow = 2)
     [,1] [,2]
[1,]   13    5
[2,]   20    8

Leave a ReplyCancel reply