Akis
Akis

Reputation: 130

Avoid a for loop

I am trying to optimize an algorithm and I really want to avoid all my loops. Hence I am wondering if there is a way to avoid the following simple loop:

library(FNN)
data <- cbind(1:10, 1:10)

NN.index <- get.knn(data, 5)$nn.index
bc <- matrix(0, nrow(NN.index), max(NN.index))
for(i in 1:nrow(bc)){
  bc[i,NN.index[i,]] <- 1
}

were bc is a matrix of zeros.

Upvotes: 0

Views: 69

Answers (1)

Po C.
Po C.

Reputation: 688

In R, if the bracket of a matrix M take a k-by-2 matrix 'I', then each row of the k-by-2 matrix I is recognized as the row and column index of M. For example

M = matrix(1:20, nrow =4, ncol = 3)
print(M)
I = rbind(c(1,2), c(4,2), c(3,3))
print(M[I])

In this case, M[1,2], M[4,2] and M[3,3] are extracted. In your case, we can create row_index and col_index from NN.index as below, and then assign 1 to the corresponding entries.

bc <- matrix(0, nrow(NN.index), max(NN.index))
row_index <- rep(1:nrow(NN.index), times = ncol(NN.index))
col_index <- as.vector(NN.index)
bc[cbind(row_index, col_index)] <- 1
print(bc)

Upvotes: 1

Related Questions