<div>Hello, </div><div> I have a discrete time markov chain function in R which I need to apply to every element of a </div><div>large Matrix.Following is teh function I have in R.</div><div>Sincs it is running a bit slow (I need to run this function over a large numeber of timesteps)</div>
<div>So, I am to used the Rcpp package to write this part of the code in C++ </div><div>I can write second function in C++ but the "transitionFun" I have no idea how to write.</div><div>The main problem for me is the "sample" function of R, which I could not implement in Rcpp.</div>
<div>Any help will be greatly appreciated.</div><div><br></div><div>#################################</div><div>transitionFun = function(stateNum, oldState, probMatrix){</div><div>  colnames(probMatrix) = as.character(1:stateNum-1)</div>
<div>  rownames(probMatrix) = as.character(1:stateNum-1)</div><div><br></div><div>  newState = sample(colnames(probMatrix), 1,</div><div>            prob = probMatrix[as.character(oldState), ])</div><div>  return(newState)</div>
<div>} </div><div><br></div><div><br></div><div>tranMat = matrix(c(0.9, 0.1, 0.1, 0.9), ncol = 2);</div><div>stateNum = 2;</div><div>states = c(0, 1);</div><div>######Original state a 100x100 matrix of 1s and 0s.</div><div>
<br></div><div>simulateMc<- function (oldMatrix, stateNum, transMat) {</div><div>oldMatrix<- matrix(0, 100, 100);</div><div><br></div><div>newMatrix<- matrix(NA, nrow(oldMatrix), ncol(oldMatrix));</div><div> for (a in 1:nrow(newMatrix)){</div>
<div><span class="Apple-tab-span" style="white-space:pre">      </span>for(b in 1:ncol(newMatrix)){</div><div>     newMatrix[a, b]  = transitionFun(stateNum, oldMatrix[a, b], transMat);</div><div>  }</div><div>}</div><div>return(newMatrix);</div>
<div>}</div><div><br></div><div><br></div>-- <br>Acharya, Subodh<br>