# For loop matrix index

**URL:** <https://discourse.processing.org/t/for-loop-matrix-index/31508>\
**Category:** Coding Questions\
**Created:** [July 31, 2021, 4:27am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508 "2021-07-31T04:27:24Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)\
**Post date:** [August 1, 2021, 1:51pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/3 "2021-08-01T13:51:07Z")

</div>

The problem seems to me that you are using the index `i` to determine both the value to display and the position to display it. Since you want to change the order the numbers are displayed there is no simple formulae linking the value to position, you need a more elaborate algorithm.  
If we number the rows and columns in the initial state we have  
 ![g1](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/0/08dc76acda1f96d46b98b38f0762bfb53aa6f976.png)

The display position of any cell is determined using `c` and `r`.

To calculate the _value_ to be displayed I will introduce 2 new variables `c1` and `r1` as it will simplify the problem later. I also introduce a new variable `gs` which is the grid square size, in this example, 4

So in the initial state we calculate the value to be stored with  
`c1 = c; r1 = r; v = 1 + c1 + r1 * gs;`

Now if we look at the other 3 grids

 ![g3](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/b/bdfcff6f34e4d3b1cc1c912ea7e376ee372f45f8.png)

The first is flipped horizontally so use  
`c1 = gs - c - 1; r1 = r; v = 1 + c1 + r1 * gs;`

the second is flipped vertically so use  
`c1 = c; r1 = gs - r - 1; v = 1 + c1 + r1 * gs;`

and the final one flipped in both directions so use  
`c1 = gs - c - 1; r1 = gs - r - 1; v = 1 + c1 + r1 * gs;`

So use a double loop like this replacing the ??? depending on which grid you are using.

```auto
  for (int r = 0; r < grid_size; r++) {
    int r1 = ?????;
    for (int c = 0; c < grid_size; c++) {
      int c1 =?????;
      int v = 1 + c1 + r1 * grid_size;
      float x = (c + 0.5) * itemSize;
      float y = (r + 0.5) * itemSize;
      fill(-1);
      square(x, y, itemSize * 0.8);
      fill(0);
      textSize(40);
      text(v, x, y);
    }
  }

```

I have tested this and it works fine.

---

_[View the full topic](https://discourse.processing.org/t/for-loop-matrix-index/31508)._
