Skip to content

Matrix element-by-element multiplication

3 messages · waddawanna, Rolf Turner, David Winsemius

#
Hello Steven,

It looks like, there is no in-built function that can do GAUSS ".*"
element-wise multiplication.
Now, if you want to make the desired computations in R, it is actually
preatty straightforward.
That, should work fine. But, suppose that for some reason you have following
situation, which can make you trip for hours of sleepless nights. That is,
you have a matrix "b", where number of columns equal to number of columns of
your vector "a". That is
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[,1] [,2] [,3]
[1,]    1    2    3

If you try to do elementwise multilication, i.e., of those two
You get an error that they are not comfomable, that is why, you have to
write your own function (here, 
I just write the for-loop):
foo[ ,i] = ( foo[ ,i] * bar[1,i] ) ;
   }
       [,1] [,2] [,3]
[1,]    1    4    9
[2,]    4   10   18
[3,]    7   16   27

I hope that this helped
Serge Boris Nesterenko
CEO 50 Pence Music Production
https://www.linkedin.com/in/sergenesterenko



--
View this message in context: http://r.789695.n4.nabble.com/Matrix-element-by-element-multiplication-tp3992206p4712964.html
Sent from the R help mailing list archive at Nabble.com.
#
On 30/09/15 12:49, waddawanna wrote:
(1) You're making heavy weather by using rep() totally unnecessarily.


(2) The example you give can be done much more succinctly; for-loops
are unnecessary:

    t(as.vector(a)*t(b))

(3) Please don't post to R-help via nabble (WTF ever that is).  It 
messes up everything.

cheers,

Rolf Turner
#
On Sep 29, 2015, at 4:49 PM, waddawanna wrote:

            
You should not have gotten that error with either `*` or `%*%`.
You were expecting c(1,2,3) to be a row-vector. That leads to disappointment. If anything it will be a column-vector.

Notice .... no error:
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    8   10   12
[3,]   21   24   27


You really wanted to sweep that vector
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    8   10   12
[3,]   21   24   27
[,1] [,2] [,3]
[1,]    1    4    9
[2,]    4   10   18
[3,]    7   16   27