I need to access and assign single slots of an m*n matrix inside a for loop. The code so far:
rowCount <- 9
similMatrix = matrix(nrow = rowCount - 1, ncol = rowCount)
show(similMatrix)
for(i in (rowCount - 1)){
for (j in rowCount)
if (i == j){
similMatrix[i == j] <- 0;
}
}
show(similMatrix)
so if i = j the NA value in the matrix needs to be replaced with 0.
For the purpose of setting the “diagonal” elements to zero you have already been given an answer but I wonder if you were hoping for something more general. The reasons for lack of success with that code were two-fold: the construction of your indices were flawed and the indexing was wrong. This would have succeeded:
But resorting to loops in R is generally considered a last resort (sometimes for the wrong reasons.) There is a much more compact way of doing the same “loop” operation and it generalizes more widely than just setting the diagonal.
If you wanted to set the subdiagonal to zero you could just use:
You can avoid generating the extra row and col matrices using this: