Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Allow "hidden" scalar multiplication in R

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

C=A*B

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C=A %*% B

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

1 %*% diag(5)

outputs

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)

Tests:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading