Avoidance of loop in matrix index

dist is an nxn cost matrix:

dist <-matrix(c(0,3.2,1.2,3.2,0,0.5,1.2,0.5,0),nrow=3,ncol=3)

v is a vector of length n, where the index of the vector corresponds to the row dist, and the value in the vector corresponds to the column dist

v <- c(2,2,3)

I want to summarize the costs as follows:

cost <- 0

for(i in 1:length(v)){

    cost <- dist[i,v[i]] + cost

}

but it seems awkward and slow. What is the trick for this without a for loop? Is the for loop not using any magic alternative to R? Suggestions please!

+4
source share
1 answer

We need cbindwith the row index to extract the values ​​andsum

sum(dist[cbind(1:nrow(dist), v)])
+4
source

Source: https://habr.com/ru/post/1695105/


All Articles