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

Ingo Reinhold ingor at kth.se
Wed Aug 8 08:03:19 CEST 2012


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

Thanks for taking a look. 

Cheers, 

Ingo

________________________________________
From: Jeff Newmiller [jdnewmil at dcn.davis.CA.us]
Sent: Wednesday, August 08, 2012 6:40 AM
To: Ingo Reinhold; r-help at r-project.org
Subject: Re: [R] Outer product from matrix by row and a vector

Can you post what you want your answer to be for the a and b you have given already?
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.

Ingo Reinhold <ingor at kth.se> wrote:

>Dear all,
>
>I am facing a challenge when applying the outer product with a matrix
>by rows.
>
>What I have is a rather big matrix, which I would like to convert into
>a different matrix by doing something like
>
>outer(matrix_row, vector, function(x,y) x[1]+5*x[4]/y)
>
>In order to get there, I tried to get the matrix into a list using the
>mefa package, as subsetting the original data appears too complicated.
>However, if I apply the following code I always get a dimensional
>error, as the unlist() function is applied to the whole list.
>
>library(mefa)
>a<-matrix(c(1:6),ncol=3)
>b<-c(1,2,3,4)
>a<-mat2list(a,MARGIN=1)
>
>outer(a,b,function(x,y){unlist(a)[1]+unlist(a)[3]/b})
>
>
>Any idea how to do this more elegantly than a nested for-loop?
>
>Many thanks,
>
>Ingo
>
>       [[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list