[Rcpp-devel] Matkov chain simulation with Rcpp
Subodh Acharya
shoebodh at gmail.com
Mon Feb 4 04:34:04 CET 2013
Hello,
I have a discrete time markov chain function in R which I need to apply to
every element of a
large Matrix.Following is teh 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 in C++ but the "transitionFun" I have no idea
how to write.
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);
}
--
Acharya, Subodh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130203/b19fe617/attachment.html>
More information about the Rcpp-devel
mailing list