The problem is that you loop from row b
to row n*b
(with stride b
, due to the precedence of *
and :
) and then index to one greater, so you attempt to index row n*b + 1
of R
, which is out of bounds.
R[0,]<-
will cause incorrect results but not elicit an error from R.
I find the code easier to read if you loop from 2
to n*b
, the number of rows, and write the formula in terms of creating row i
from row i-1
(rather than creating row i+1
from row i
).
In addition, you can drop one loop dimension by vectorizing the operations over the rows:
HRC <- function(n, b, c) {
R <- matrix(NA, nrow = n*b, ncol = c)
R[1,] <- 133
r <- matrix(rnorm(n*b*c), ncol=c)
for (i in 2:(n*b)){
R[i,] <- R[i-1,] + 3*b/r[i-1,]
}
return(R)
}
HRC(10,1,3)
Here, the same number of random samples are taken with rnorm
but they are formed as a matrix, and used in the same order as used in the question. Note that not all of the random values are actually used in the computation.
If you set a random seed and then run this function, and the function in @flodel's answer, you will get identical results. His answer is also correct.