0

my first question on Stack Overflow.

I'm trying to update a 25x25 matrix representing states in a 5x5 grid. The rows represent current states, columns represent the next state. I'm using a formula given below to assess the adjacency of a given state to another given state by their coordinates. The aim is to then use those coordinates to update the 25x25 state matrix with 1's where moving from one numbered state in the 5x5 grid to it's adjacent state is possible.

|x1−x2|≤1 and |y1−y2|≤1

No errors, and only the T[25,25] element is updating. Any ideas why this isn't working properly?

T = matrix(c(1:25),nrow=5,ncol=5, byrow=T)
S = matrix(0,nrow=25,ncol=25)
for (i in nrow(T)){
    for (j in ncol(T)){
        for (f in nrow(T)){
            for (g in ncol(T)){
                if ((abs(i-f) <= 1) & (abs(j-g) <= 1)){
                    S[T[i,j], T[f,g]] = 1
                    }}}}}
T-Rone
  • 1
  • 3
  • Please include in your question the exact output you are expecting to get and what you are getting instead. Readers shouldn't have to go somewhere else to understand what you are trying to do. Also, it is terrible idea to overload built-in's such as `T`. Notice that you are using it both for the boolean `TRUE` and for the matrix. Furthermore, 4 nested loops is equally terrible design... maybe you can improve that once you figure out what's wrong. – iled Feb 28 '17 at 17:18
  • In all of your for loops you are missing the `1:`. You should have `i in 1:nrow(T))` and similar for the rest. – Travis Feb 28 '17 at 17:22
  • Thank you Travis, silly mistake! Now it works like a charm. If you would like to put this as the answer I will approve it. Thank you for your criticisms iled, I have now included the equation I used, as for the terrible design, any advice on how to improve this would be greatly appreciated. – T-Rone Feb 28 '17 at 17:28

0 Answers0