0

I ran some code:

size <- 5
G < -matrix(c(0,1,0,0,1,
              1,0,1,1,0,
              0,1,0,1,1,
              0,1,1,0,1,
              1,0,1,1,0), ncol=size)

# Max <- rep(0,4)
delta <- 0.299
results <- rep(0,16)
results <- matrix(results, ncol=4)
p <- 1
record <- NULL
for (i in 1:(size-1))
 {
  for(j in (i+1):size )
   {
     GAA <- matrix(c(G[i,i], G[j,i], G[i,j], G[j,j]), ncol=2)
     GAB <- rbind(G[i, c(-i,-j)], G[j, c(-i,-j)])
     GBA <- t(GAB)
     GBB <- G[c(-i,-j),c(-i,-j)]
     I <- diag(dim(GBB)[1])
     U <- solve(I-delta*GBB)
     T <- GAA+delta*GAB%*%U%*%GBA
     TD <- diag(diag(T))
     IT <- diag(dim(T)[1])
     S11 <- solve(IT-delta*(T+TD))
     S12 <- delta*S11%*%GAB%*%U
     S21 <- t(S12)
     S22 <- U + delta^2 * U %*% GBA %*% S11 %*% GAB %*% U
     Total <- sum(rbind(cbind(S11,S12), cbind(S21,S22)))
     record <- rbind(record, c(Total,i,j))
   }
 }
 record

from the record, I can see:

           [,1] [,2] [,3]
 [1,]  124.0335    1    2
 [2,] -210.0012    1    3
 [3,] -210.0012    1    4
 [4,]  124.0335    1    5
 [5,]  247.8299    2    3
 [6,]  247.8299    2    4
 [7,] -273.4414    2    5
 [8,]  163.5456    3    4
 [9,]  247.8299    3    5
[10,]  247.8299    4    5

which shows there are four rows giving the highest sum (rows [5],[6],[9],[10]). However, after I run the following code:

Max <- max(record[,1])
for(l in 1:(size*(size-1)/2))
 {
   if (record[l,1]==Max)
   {
     results[p,] <- c(record[l,],delta)
     p <- p+1}
 }
results:
         [,1] [,2] [,3]  [,4]
[1,] 247.8299    2    3 0.299
[2,] 247.8299    2    4 0.299
[3,]   0.0000    0    0 0.000
[4,]   0.0000    0    0 0.000

I only catch rows [5] and [6]; I am missing rows [9] and [10] on my record. Where is the problem?

Keyu Nie
  • 41
  • 1
  • 1
  • 4
  • 4
    Are you asking about how to improve the code, or about the underlying math that you are attempting to implement via the code? (Neither is on-topic here, but your answer will help us migrate this question to the appropriate venue.) – gung - Reinstate Monica Aug 01 '14 at 22:02
  • my bad, check the "record": there should be 4 maximum output, however, check my "results", I only get two. –  Aug 02 '14 at 06:12
  • 1
    If you print out the *differences* between the results and the maximum you might see what the problem is. – whuber Aug 02 '14 at 15:31
  • 3
    +1 to @whuber; try if `isTRUE(all.equal(record[l,1],Max))` or `if (abs(record[l,1]-Max)<1e-10)`, and read [R FAQ 7.31](http://www.hep.by/gnu/r-patched/r-faq/R-FAQ_82.html) – Ben Bolker Aug 02 '14 at 15:39
  • thanks all for the help. It works. – Keyu Nie Aug 02 '14 at 17:21

0 Answers0