Julija Kezina
Julija Kezina

Reputation: 11

Asking the code to stop when all values in a vector are less than 10^-8

I am very new to R programming, and I was given the following task: I have to define matrix p (8 x 1), which is updated in each iteration by multiplying it by a transpose of a matrix P (8 x 8). Then I need to compute the relative change of each entry (and create matrix r (8 x 1) with differences):

r[i] = ( | p[i] - pOld[i] | ) / p[i]

where pOld is the previous p

and terminate the loop when the all r[i] are less than or equal to 10^-8. I wrote the following code, but it would not converge. Could you please point me to a mistake? Here is my code:

p <- as.matrix(rep(1/8,8)) #creating initial matrix p           
k <- 1
r <- as.matrix(rep(1,8)) 

while (all(r > 1e-8))  {

        pOld <- p
        p <- t(P) %*% p
        r <- as.matrix(rep(1,8))        #creating empty vector r

        for (i in 1:8) {
                    value <- abs(p[i]-pOld[i])/p[i] 
                    ifelse(value<=1e-8, r[i] <- value, next)
        }   
        k <- k+1
}

P is as following:

        p1      p2      p3      p4      p5      p6      p7      p8
[1,] 0.01875 0.86875 0.01875 0.01875 0.01875 0.01875 0.01875 0.01875
[2,] 0.44375 0.01875 0.01875 0.01875 0.01875 0.01875 0.44375 0.01875
[3,] 0.01875 0.44375 0.01875 0.44375 0.01875 0.01875 0.01875 0.01875
[4,] 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500
[5,] 0.01875 0.01875 0.01875 0.44375 0.01875 0.44375 0.01875 0.01875
[6,] 0.01875 0.23125 0.23125 0.23125 0.23125 0.01875 0.01875 0.01875
[7,] 0.01875 0.01875 0.01875 0.01875 0.01875 0.44375 0.01875 0.44375
[8,] 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500 0.12500

Upvotes: 0

Views: 49

Answers (1)

jogo
jogo

Reputation: 12559

Eventually the complete code could be:

P <- matrix(c( 
0.01875, 0.86875, 0.01875, 0.01875, 0.01875, 0.01875, 0.01875, 0.01875,
0.44375, 0.01875, 0.01875, 0.01875, 0.01875, 0.01875, 0.44375, 0.01875,
0.01875, 0.44375, 0.01875, 0.44375, 0.01875, 0.01875, 0.01875, 0.01875,
0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500,
0.01875, 0.01875, 0.01875, 0.44375, 0.01875, 0.44375, 0.01875, 0.01875,
0.01875, 0.23125, 0.23125, 0.23125, 0.23125, 0.01875, 0.01875, 0.01875,
0.01875, 0.01875, 0.01875, 0.01875, 0.01875, 0.44375, 0.01875, 0.44375,
0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500, 0.12500), 8, 8, byrow=TRUE)

p <- rep(1/8, 8) #creating initial matrix p           
k <- 1

while (any(r > 1e-8)) { #  
  pOld <- p
  p <- c(crossprod(P, p)) ## t(P) %*% p
  r <- rep(1, length(p))

  v <- abs(p-pOld) / p
  r <- ifelse(v<=1e-8, v, r)
  k <- k+1
}

Upvotes: 1

Related Questions