# [Rcpp-devel] Markov chain transition in Rcpp

Subodh Acharya shoebodh at gmail.com
Mon Feb 4 04:31:49 CET 2013

```Hello,
I have a markov chain function in R which I need to apply to every element
of a
large Matrix.Following is the function I have in R.
Sincs it is running a bit slow (I need to run this function over a large
numeber of timesteps)
So, I am to used the Rcpp package to write this part of the code in C++
I can write second function ("simulateMC") in C++ but the "transitionFun" I
could not.
The main problem for me is the "sample" function of R, which I could not
implement in Rcpp.
Any help will be greatly appreciated.

#################################
transitionFun = function(stateNum, oldState, probMatrix){
colnames(probMatrix) = as.character(1:stateNum-1)
rownames(probMatrix) = as.character(1:stateNum-1)

newState = sample(colnames(probMatrix), 1,
prob = probMatrix[as.character(oldState), ])
return(newState)
}

tranMat = matrix(c(0.9, 0.1, 0.1, 0.9), ncol = 2);
stateNum = 2;
states = c(0, 1);
######Original state a 100x100 matrix of 1s and 0s.

simulateMc<- function (oldMatrix, stateNum, transMat) {
oldMatrix<- matrix(0, 100, 100);

newMatrix<- matrix(NA, nrow(oldMatrix), ncol(oldMatrix));
for (a in 1:nrow(newMatrix)){
for(b in 1:ncol(newMatrix)){
newMatrix[a, b]  = transitionFun(stateNum, oldMatrix[a, b], transMat);
}
}
return(newMatrix);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130203/549aa0d4/attachment-0001.html>
```