I use R and I implemented a Monte Carlo simulation in R which takes long time because of the for loops. Then I realized that I can do the for loops in C, using R API. So I generate my vectors, matrices in R then I call functions from C(which will do the for loops) and finally I present my results in R. However, I only know the basics of C and I cannot figure how to transform some functions to C. For instance I start with a function in R like this:
t=sample(1:(P*Q), size=1)
How can I do this in C? Also I have an expression in R:
A.q=phi[,which(q==1)]
How can I use “which” expression in C?
Before you start writing C code, you would be better off rewriting your R code to make it run faster.
sampleis vectorised. Can you move the call to it outside the loop? That should speed things up. Even better, can you get rid of the loop entirely?Also, you don’t need to use
whichwhen you are indexing. R accepts logical vectors as indicies. Compare:Finally, I recommend not calling your variables
torqsince there are functions with those names. Try giving your variables descriptive names instead – it will make your code more readable.