I have been given a matrix:
P <- matrix(c(0, 0, 0, 0.5, 0, 0.5, 0.1, 0.1, 0, 0.4, 0, 0.4, 0, 0.2, 0.2, 0.3, 0, 0.3, 0, 0, 0.3, 0.5, 0, 0.2, 0, 0, 0, 0.4, 0.6, 0, 0, 0, 0, 0, 0.4, 0.6), nrow = 6, ncol = 6, byrow = TRUE)
Using functions, mpow , rows_equal , matrices_equal . I want to find when P^n converges, in other words, what n is when all rows are equal in the matrix and when P^n = P^(n+1) .
Just looking at the functions i , it was possible to deduce that around n=19-21 matrix will converge.
Although, I want to find the correct n using a loop. Here are the mpow , rows_equal and matrices_equal functions. I know that they can be written in different ways, but please keep them as they are.
mpow <- function(P, n, d=4) { if (n == 0) diag(nrow(P))) else if (n== 1) P else P %*% mpow(P, n - 1)) } rows_equal <- function(P, d = 4) { P_new <- trunc(P * 10^d) for (k in 2:nrow(P_new)) { if (!all(P_new[1, ] == P_new[k, ])) { return(FALSE)} } return(TRUE) } 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)) TRUE else FALSE }
Now, to write a loop, we have to do something line by line:
First, create this function:
when_converged <- function(P) {...}
and
for (n in 1:50)
Try when t.ex n = 50.
Although I do not know how to write code for this correctly, can someone help me with this?
Thanks for reading my question.