[R] Outer product from matrix by row and a vector

David Winsemius dwinsemius at comcast.net
Wed Aug 8 15:05:41 CEST 2012


On Aug 7, 2012, at 11:26 PM, Petr Savicky wrote:

> On Wed, Aug 08, 2012 at 06:03:19AM +0000, Ingo Reinhold wrote:
>> Hi Jeff, David,
>>
>> what I'm trying to do is speed the currently used nest for loop
>>
>> a<-matrix(c(1:6),ncol=3)
>> b<-c(1,2,3,4)
>>
>> result<-matrix(rep(0, times=dim(a)[1]*length(b)),nrow=dim(a)[1])
>> for(ii in 1:dim(a)[1]){
>>  for(jj in 1:length(b)){
>>    result[ii,jj]<-a[ii,1]+a[ii,3]/b[jj]
>>      }
>> }
>>
>> giving the result
>>
>>     [,1] [,2] [,3]
>> [1,]    1    3    5
>> [2,]    2    4    6

That is not what result equals (as Petr illustrates.)

>
> Hi.
>
> The printed matrix is "a". The above code yields on my computer
>
>       [,1] [,2]     [,3] [,4]
>  [1,]    6  3.5 2.666667 2.25
>  [2,]    8  5.0 4.000000 3.50
>
> Try the following
>
>  out <- a[, 1] + a[, 3] %o% (1/b)
>
>  max(abs(out - result))
>
>  [1] 4.440892e-16
>
> Hope this helps.

It's also the case that the printed result is just the transpose of  
what I earlier offered as a possible implementation of the OP's pseudo- 
code.:

 > identical( t( apply(a, 1, function(x) { x[1] + x[3]/ b } ) ), result)
[1] TRUE

-- 

David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list