Skip to content

Matrix element-by-element multiplication

3 messages · michael.weylandt at gmail.com (R. Michael Weylandt, Steven Yen, Joshua Wiley

#
Hi,

R may not have a special "scalar", but it is common, if informal, in
linear algebra to refer to a 1 x 1 matrix as a scalar.  Indeed,
something like:

1:10 * matrix(2)
or
matrix(2) * 1:10

are both valid.  Even

matrix(2) %*% 1:10
and
1:10 %*% matrix(2)

work, where the vector seems to be silently coerced to a matrix.  R
even seems to work hard to convert to a conformable matrix:

## works:
1:10 %*% matrix(1:10)
## does not work
matrix(1:10) %*% matrix(1:10)
## works
t(matrix(1:10)) %*% matrix(1:10)

Interestingly, there is actually a (rather old) comment in arithmetic.c

    /* If either x or y is a matrix with length 1 and the other is a
       vector, we want to coerce the matrix to be a vector.
       Do we want to?  We don't do it!  BDR 2004-03-06
    */

Given the coersion that already occurs with vectors to matrices for
%*% and matrices to vectors for *, it seems not unreasonable to
convert a 1 x 1 matrix to a vector _for_ * so that the following
yields identical results:

matrix(1:9, 3) * matrix(2)
matrix(1:9, 3) * 2

Of course in the mean time, or in general, it is a good habit to
create or explicity coerce objects yourself rather than relying on R
to make smart guesses about what should be happening.

Cheers,

Josh

On Sun, Nov 6, 2011 at 4:02 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> <michael.weylandt at gmail.com> wrote: