[R] Strange Matrix Multiplication Behaviour
Gavin Simpson
gavin.simpson at ucl.ac.uk
Mon Oct 4 17:34:50 CEST 2004
Wayne Jones wrote:
> Hi there fellow R-users,
>
> Im seeing some strange behaviour when I multiply a vector by a matrix
>
> Here is my script:
>
"*" does array or element-wise multiplication. %*% is Matrix multiplication.
In the first case, you are multiplying tr by the first row of ex1
> tr * ex1[1, ]
a b c d e f
1 0.05122422 -0.5117032 -0.09961093 -0.1842568 0.03664727 -0.2285117
In the second, you are extracting the first row of the result of
multiplying tr by ex1, which as we see below returns a 2x6 matrix:
> tr * ex1
a b c d e f
1 0.05122422 -0.4878917 -0.10648873 -0.24451059 0.03428033 -0.24698556
2 -0.04471461 -0.4211459 -0.01675805 -0.05573933 -0.44671804 -0.04852005
> (tr * ex1)[1, ]
a b c d e f
1 0.05122422 -0.4878917 -0.1064887 -0.2445106 0.03428033 -0.2469856
Note that tr gets recycled in the tr * ex1 and (tr * ex1)[1, ] as tr is
not as long as ex1.
Element 1b in (tr * ex1)[1, ] is formed by multiplying element 1b of ex1
(-3.279045) by the third element of the vector tr (0.1487908):
> tr[3] * ex1[1,2]
[1] -0.4878917
the second value of the vector tr was used to multiply against element
2a in matrix ex1:
but in the tr * ex1[1, ] case tr and ex1[1, ] both contain 6 elements
and the element 1b in the results is formed by multiplying element 1b of
ex1[1, ] (-3.279045) by the second element of vector tr (0.1560525)
> tr[2] * ex1[1,2]
[1] -0.5117032
>
> Notice that the output from tr * ex[1,] is different from (tr* ex1)[1,]
> Especially element number 4.
The difference is due to recycling of tr and of where you are doing your
sub setting
> I would naturally expect both vectors to be equivalent.
>
Hopefully my longwinded explanation helps.
Gav
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Gavin Simpson [T] +44 (0)20 7679 5522
ENSIS Research Fellow [F] +44 (0)20 7679 7565
ENSIS Ltd. & ECRC [E] gavin.simpson at ucl.ac.uk
UCL Department of Geography [W] http://www.ucl.ac.uk/~ucfagls/cv/
26 Bedford Way [W] http://www.ucl.ac.uk/~ucfagls/
London. WC1H 0AP.
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
More information about the R-help
mailing list