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

Petr Savicky savicky at cs.cas.cz
Wed Aug 8 08:26:02 CEST 2012


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

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.

Petr Savicky.



More information about the R-help mailing list