Advertisement
juaniisuar

ej4 tproba v2

Jul 2nd, 2017
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. library("markovchain")
  2.  
  3. matrix.power <- function(A, n) {
  4. if(n == 0)
  5. return(diag(dim(P)[1]))
  6. e <- eigen(A)
  7. M <- e$vectors
  8. d <- e$values
  9.  
  10. if(length(M) == dim(P)[1]) # si es diagonalizable
  11. return(M %*% diag(d^n) %*% solve(M))
  12. else{
  13. newA = diag(dim(P)[1])
  14. for(i in 1:n)
  15. newA = newA %*% A
  16. return(newA)
  17. }
  18. }
  19.  
  20. S = c("A", "B", "C", "D")
  21.  
  22. mu0 = c(1/8, 2/8, 1/8, 4/8)
  23.  
  24. P = matrix(
  25. c(0.1, 0.1, 0.8, 0,
  26. 0.4, 0 , 0.5, 0.1,
  27. 0.1, 0 , 0 , 0.9,
  28. 0.4, 0.1, 0.5, 0),
  29. nrow = 4,
  30. ncol = 4,
  31. byrow = TRUE
  32. )
  33.  
  34. if( sum(mu0) != 1 ) #el vector de distrib. inicial k debe sumar 1
  35. stop( "Las probabilidades del vector inicial no suman 1" )
  36.  
  37. for(i in 1:dim(P)[1]){
  38. if( sum (P[i,]) != 1) #las filas deben sumar 1
  39. stop( "Las filas individuales de P no suman 1" )
  40.  
  41. if( P[i,i] == 1 ) #no debe haber estados absorbentes por enunciado
  42. stop( "Hay algún estado absorbente presente" )
  43. }
  44.  
  45. Q = new("markovchain", transitionMatrix = P,
  46. states = S, name = "Buffer")
  47.  
  48. plot(Q, main = "Cadena de Markov", edge.arrow.size=0.5)
  49.  
  50. #simulate
  51. tests=10000
  52. n = 100
  53.  
  54. T = markovchainSequence(n, Q, t0 = sample(Q@states, prob = mu0, replace = TRUE, 1), include.t0 = TRUE)
  55. plot(0:n, factor(T), yaxt = "n", main = "Simulación de una Trayectoria", ylab = "Estado", xlab = "Tiempo", type = "l", col = "blue")
  56. axis(side=2, at = 1:4, labels = S)
  57.  
  58. R = c(0, 0, 0, 0)
  59. names(R) = S
  60. T
  61. for(i in T)
  62. R[i] = R[i] + 1
  63.  
  64. print("Numero de visitas a los nodos (en n=100 pasos) simulada: ")
  65. print(R)
  66.  
  67. #newP = P^n
  68. newP = matrix.power(P, n)
  69. muN = mu0 %*% newP #probabilidad de estar en el i-esimo nodo luego de 'n' pasos
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement