[R] Matrix element-by-element multiplication

David Winsemius dwinsemius at comcast.net
Wed Sep 30 06:25:38 CEST 2015


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

> 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.
> 
>> a<-c(1,2,3)
>> b<-matrix(rep(1:9,1),3,3,byrow=TRUE)
>> a*b
> 
> 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
> 
>> b<-matrix(rep(1:9,1),3,3,byrow=TRUE);b
>     [,1] [,2] [,3]
> [1,]    1    2    3
> [2,]    4    5    6
> [3,]    7    8    9
> 
>> a <- matrix(rep(1:3,1),1,3,byrow=TRUE)
>     [,1] [,2] [,3]
> [1,]    1    2    3
> 
> If you try to do elementwise multilication, i.e., of those two
>> b*a
> 
> You get an error that they are not comfomable,

You should not have gotten that error with either `*` or `%*%`.

> that is why, you have to
> write your own function (here, 
> I just write the for-loop):
>> for ( i in 1:3 ) {
>     foo[ ,i] = ( foo[ ,i] * bar[1,i] ) ;
>   }
>       [,1] [,2] [,3]
> [1,]    1    4    9
> [2,]    4   10   18
> [3,]    7   16   27

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:
> a*b
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    8   10   12
[3,]   21   24   27


You really wanted to sweep that vector

> sweep(b, 1,a,'*')   # Sweeping by rows is same a multiplying by recycle column vector 
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    8   10   12
[3,]   21   24   27

> sweep(b, 2, a, '*')  # You wanted to "sweep" across columns
     [,1] [,2] [,3]
[1,]    1    4    9
[2,]    4   10   18
[3,]    7   16   27

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list