I have a matrix:
P <- matrix(c(0, 0.5, 0, 0, 0.5, 0,
0.5, 0, 0.5, 0, 0, 0,
0, 0.5, 0, 0.5, 0, 0,
0, 0, 0.5, 0, 0, 0.5,
0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1),
nrow = 6, ncol = 6, byrow = TRUE)
Can anyone help me with the code to find the n that makes P^n = P^n+1
with an accuracy of 4 decimal places.
The code under here, is how I´ve attempted the problem. Although, I'm not so good at coding so the last part is not correct. Is there something that i can add to it so it works? Or is there another way to solve it? If so please explain the code you write.
mpow <- function(P, n) {
if (n == 0) {
return(diag(nrow(P)))}
else if (n == 1){
return(P)
} else {
return(P %*% mpow(P, n - 1))
}
}
matrices_equal <- function(A, B, d = 4) {
A_new <- trunc(A * 10^d)
B_new <-trunc(B * 10^d)
if (all(A_new == B_new)) {
return(TRUE) }
else {
return(FALSE) } }
when_converged <- function(P)
for (n in 1:50) {{
A <- mpow(P, n)
B <- mpow(P, n+1)
}
{ if matrices_equal(A, B, 4)
return(n)
}}
Thank you.