Mark
Mark

Reputation: 1769

How can I speed a double for loop in R

I have the following R code. The function Heaviside2 is the Heaviside step function, while the matrix A is a matrix of data.

for (i in 1:N){
   for (j in 1:N){
      if (j!=i) {
          arg=r-normvec(A[i,]-A[j,])
          s=s+Heaviside2(arg)
      }
   }
}

I try to speed this code, deleting the double for, but the inner "if" makes it more difficult.

Thanks in advance

Upvotes: 1

Views: 105

Answers (1)

Iaroslav Domin
Iaroslav Domin

Reputation: 2718

In your case dist function is very helpful. So I think the solution would be

sum(Heaviside(r - dist(A)))

I don't know what Heaviside function are you using, but I'm using the one from fBasics package.

Upvotes: 2

Related Questions