2

I am using two for loops to establish a covariance matrix in R. I have 2 data vectors and a covariance function f(x) between every 2 data points. My code is like this:

r12=function(x1,x2,H){
  ra12= matrix(0,length(x1),length(x2))
  for (i in 1:nrow(ra12)) 
  {
    for (j in 1:ncol(ra12)) 
    {
      raed12[i,j]=fx(x1[i]-x2[j],H)
    }
  }
  return(raed12)
}

How can I make this code faster?

raK1
  • 519
  • 1
  • 4
  • 13
  • For starters, how about changing your inner for loop so as to only compute the lower or upper triangle of the covariance matrix? – Mark L. Stone Feb 24 '16 at 01:29
  • 2
    Is `fx` vectorized? If so, your code looks like longhand for computing an outer product. See the help for `outer`. – whuber Feb 24 '16 at 01:30
  • @MarkL.Stone I had originally posed that as an answer, but I think that there are two different vectors, i.e. it may be a rectangular Gram matrix when x1 != x2. – Sycorax Feb 24 '16 at 04:00

1 Answers1

1

Consider an sapply() solution, passing in multiple arguments assuming fx() is vectorized:

r12 <- function(x1,x2,H){
          return(fx(x1-x2,H))
       }
mat <- sapply(vector1, r12, vector2, H)
Community
  • 1
  • 1
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • I really thank you a lot, you have saved me a lot of time really – raK1 Feb 25 '16 at 02:52
  • It seems I do not need to Vectorize the function , also when I vectorize it is gives an error , can you explain that ? – raK1 Feb 25 '16 at 02:53