# 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:** 15
**Page:** 1

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [July 31, 2021, 4:27am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/1 "2021-07-31T04:27:24Z")

</div>

```auto
int total;
float itemSize;

void setup() {
  size(800, 800); 
  pixelDensity(2);
  smooth();
  rectMode(CENTER);

  total = 4;
  itemSize = width/total;
}

void draw() {
  clear();
  for (int i = 0; i < sq(total); i ++) {
    float x = i % total * itemSize + itemSize/2;
    float y = i / total * itemSize + itemSize/2;
    fill(-1);
    square(x, y, itemSize * 0.8);

    fill(0);
    textSize(40);
    text(i+1, x, y);
  }
}

```

 ![sketch_127_MatrixIndex_01_049](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/a1799dd79669928d3ee646341f2ba68042cdf05a.png)

Currently I can do this step, but there is no way to sort it in reverse order.

This is my attempt, `for (int i = sq(total); i >= 0; i --) {}` is there something wrong with my calculation method?

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/5/576cbba561c9f7b74694cac3c977bf23b07db5d8.png)

How do I achieve the flashback effect in the schematic, please?

Thank you so much for your help!

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [July 31, 2021, 2:29pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/2 "2021-07-31T14:29:42Z")

</div>

> [@niuuin](#):
>
> This is my attempt, `for (int i = sq(total); i >= 0; i --) {}` is there something wrong with my calculation method?

See error:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/c/cee9cec84e56a399e4a9f171c1b9d93d41878f9f.png)

`sq()` returns a `float`:  
[https://processing.org/reference/sq\_.html](https://processing.org/reference/sq_.html)

Try:  
`total*total` which returns an `int`

Or this to convert the `float` to an `int`:  
[https://processing.org/reference/intconvert\_.html](https://processing.org/reference/intconvert_.html)

The `i --` seemed to work once I corrected code but really should be `i--` without spaces.

> [@niuuin](#):
>
> How do I achieve the flashback effect in the schematic, please?

Consider this:

```auto
int t, total;
float itemSize;

void setup() 
  {
  size(800, 800); 
  //pixelDensity(2);
  smooth();
  rectMode(CENTER);

  total = 4;
  t = 4;
  itemSize = width/total;
  }

void draw() 
  {
  for (int i = 0; i < sq(total); i ++) 
    {
    float x = i % total * itemSize + itemSize/2;
    float y = i / total * itemSize + itemSize/2;
    fill(-1);
    square(x, y, itemSize * 0.8);

    textAlign(CENTER, CENTER);
    textSize(24);

    fill(0);
    text((i/t)%2, x, y-60);
    text(i%t, x, y-30);
    text(i, x, y);
    text(i/t, x, y+30);
    text(t-i%t, x, y+60); 
    }
  }

```

Output from above:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/f/f44b97b293e0062d02a0ba7d4ab62d0f66c7e05d.png)

From the above I was able to do some math and achieve this:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/8/88ed38e569171dcfc68372b094c880c7fead80be.png)

An `if\else` statement was used to determine _odd\even_ lines and print the correct order.

I took advantage of _integer math_ in my example above.

`:)`

---

<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.

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 2, 2021, 2:35am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/5 "2021-08-02T02:35:22Z")

</div>

Amazing! Thank you very much, I can come up with an answer along your lines, but understanding it is still a bit difficult for me, I will study and learn it carefully.

Your reply helped me a lot and I wish you all the best 🙂

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 2, 2021, 2:38am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/6 "2021-08-02T02:38:08Z")

</div>

Thank you for your reply, maybe I’m not competent enough, I wasn’t able to achieve the results as you did, I’ll keep working on it, thanks!

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 2, 2021, 3:32am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/7 "2021-08-02T03:32:58Z")

</div>

A simple package is carried out on your basis, so that four arrangements can be quickly formed.  
Thank you for the algorithm provided!

```auto
int total;
float itemSize;

void setup() {
  size(800, 800); 
  pixelDensity(2);
  smooth();
  rectMode(CENTER);

  total = 4;
  itemSize = width/total;
}

void draw() {
  clear();
  drawGrid("lt");
}

// lt -> left top
// rt -> right top
// ld -> left down
// rd -> right down
void drawGrid(String str) {
  int r1 = 0;
  int c1 = 0;
  for (int r = 0; r < total; r++) {
    if (str == "lt" || str == "rt") {
      r1 = r;
    } else if (str == "ld" || str == "rd") {
      r1 = total - r - 1;
    }

    for (int c = 0; c < total; c++) {
      if (str == "lt" || str == "ld") {
        c1 = c;
      } else if (str == "rt" || str == "rd") {
        c1 = total-c-1;
      }
      int v = 1 + c1 + r1 * total;
      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);
    }
  }
}

```

 ![Frame 13](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/9/90907b7ceb7056efac2e8fe6c1fdc5222cfee0d0.png)

algorithm by: @quark[For loop matrix index - #3 by quark](https://discourse.processing.org/t/for-loop-matrix-index/31508/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 2, 2021, 9:01am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/8 "2021-08-02T09:01:36Z")

</div>

In Java strings should not be compared with the `==` operator, instead you should use the `equals()` method so  
`str == "ld"`  
becomes  
`str.equals("id")`  
I will leave you to google it for an explanation.

Apart from that congratulations on a nice implementation.

---

<div class="post-metadata">

### Author: ![PhilHaw](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/philhaw/32/8221_2.png) [@PhilHaw](https://discourse.processing.org/u/PhilHaw)
#### Post date: [August 2, 2021, 3:57pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/9 "2021-08-02T15:57:32Z")

</div>

> [@niuuin](#):
>
> ```auto
> // lt -> left top
> // rt -> right top
> // lb -> left down
> // rb -> right down
> void drawGrid(String str) {
> 
> ```

Just to avoid any possible confusion to others, you might wish to edit the two comments just preceding drawGrid(…): ‘lb’ and ‘rb’ should be ‘ld’ and ‘rd’ respectively. Your code is correct (apart from the use of == for string comparison mentioned by @quark )

Phil.

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 3, 2021, 1:30am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/10 "2021-08-03T01:30:59Z")

</div>

Okay, thanks for the reminder. It has been modified.

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 3, 2021, 6:22am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/11 "2021-08-03T06:22:56Z")

</div>

Learned something new again, many thanks 🙂  
[Processing String\_equals](https://processing.org/reference/String_equals_.html)

```auto
String a = new String("abc");
String b = new String("abc");

println(b.equals(a));
// retuen true
println(a == b);
// retuen false

```

I have adjusted the code:

```auto
int total;
float itemSize;

void setup() {
  size(800, 800); 
  pixelDensity(2);
  smooth();
  rectMode(CENTER);
  textAlign(CENTER, CENTER);
  textSize(60);
  total = 4;
  itemSize = width/total;
}

void draw() {
  clear();
  //drawGrid("lt");
  //drawGrid("rt");
  //drawGrid("ld");
  drawGrid("rd");
}

// lt -> left top
// rt -> right top
// ld -> left down
// rd -> right down
void drawGrid(String str) {
  int r1 = 0;
  int c1 = 0;
  for (int r = 0; r < total; r++) {
    if (str.equals("lt") || str.equals("rt")) {
      r1 = r;
    } else if (str.equals("ld")|| str.equals("rd")) {
      r1 = total - r - 1;
    }

    for (int c = 0; c < total; c++) {
      if (str.equals("lt")|| str.equals("ld")) {
        c1 = c;
      } else if (str.equals("rt")|| str.equals("rd")) {
        c1 = total-c-1;
      }
      int v = 1 + c1 + r1 * total;
      float x = (c + 0.5) * itemSize;
      float y = (r + 0.5) * itemSize;
      fill(-1);
      square(x, y, itemSize * 0.8);
      fill(0);
      text(v, x, y);
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [August 3, 2021, 12:17pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/12 "2021-08-03T12:17:09Z")

</div>

Hello @niuuin,

Some suggestions:

- use if statements to determine a “choice” outside of the loop.  
_This is done once._

- use switch\case statements inside the loop.  
_Once choice is made for each step through the loop._

Example

```auto
 int choice; 

//if statements set choice

  for (int r = 0; r < total; r++) 
    {
    for (int c = 0; c < total; c++) 
      {
      choice = 0;
       switch(choice) {
      case 0: 
        r1 = r;
        c1 = c;
        break;
      case 1: 
        r1 = r;
        c1 = total-c-1;
        break;
      case 2: 
      // ???
        break;
      case 3: 
      // ?;
        break;  
      default:
        r1 = r;
        c1 = c;
        break;
        }
    // code
     } 

```

References:

- [case \ Language (API) \ Processing 3+](https://processing.org/reference/case.html)
- [switch \ Language (API) \ Processing 3+](https://processing.org/reference/switch.html)

Look up the reference for `clear()`:  
[https://processing.org/reference/clear\_.html](https://processing.org/reference/clear_.html)  
That will make things clear!

Consider this at start of `draw()`:  
[https://www.processing.org/reference/background\_.html](https://www.processing.org/reference/background_.html)

`:)`

---

<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 3, 2021, 12:43pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/13 "2021-08-03T12:43:33Z")

</div>

I would not recommend the use of a switch statement inside the inner loop although it does make sense to keep the string comparisons outside the loop. The drawGrid method below shows how to do this elegantly and efficiently.

```auto
// lt -> left top
// rt -> right top
// ld -> left down
// rd -> right down
// Any other value will be treaed as lt
void drawGrid(String str) {
  int r1 = 0;
  int c1 = 0;
  boolean flipY = str.equals("ld") || str.equals("rd");
  boolean flipX = str.equals("rt") || str.equals("rd");
  for (int r = 0; r < total; r++) {
    r1 = flipY ? total - r - 1 : r;
    for (int c = 0; c < total; c++) {
      c1 = flipX ? total-c-1 : c;
      int v = 1 + c1 + r1 * total;
      float x = (c + 0.5) * itemSize;
      float y = (r + 0.5) * itemSize;
      fill(-1);
      square(x, y, itemSize * 0.8);
      fill(0);
      text(v, x, y);
    }
  }
}

```

Note I use the ternary operator statements inside the loop like this

```auto
c1 = flipX ? total-c-1 : c;
// variable = boolean-condition ? value-if-true : value-if-false;

```

the ternary statement returns a value based on whether a condition is true so if `flipX` is true then `c1=total-c-1` but if false then `c1=c`

---

<div class="post-metadata">

### Author: ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)
#### Post date: [August 3, 2021, 2:00pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/14 "2021-08-03T14:00:30Z")

</div>

> [@quark](#):
>
> In Java strings should not be compared with the `==` operator, instead you should use the `equals()` method so

your explanation is great and easy to understand

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [August 4, 2021, 11:29am UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/15 "2021-08-04T11:29:51Z")

</div>

> [@niuuin](#):
>
> Learned something new again, many thanks 🙂  
> [Processing String\_equals](https://processing.org/reference/String_equals_.html)

Hello,

The Processing Wiki has some troubleshooting tips including this one:  
[https://github.com/processing/processing/wiki/Troubleshooting](https://github.com/processing/processing/wiki/Troubleshooting)

Another good resource:

> **[Processing 2.x and 3.x Forum](https://forum.processing.org/two/discussion/8093/frequently-asked-questions)**
>
> Processing is an electronic sketchbook, a language and a worldwide community. This is its forum.

`:)`

---

<div class="post-metadata">

### Author: ![niuuin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/niuuin/32/7517_2.png) [@niuuin](https://discourse.processing.org/u/niuuin)
#### Post date: [August 4, 2021, 12:52pm UTC](https://discourse.processing.org/t/for-loop-matrix-index/31508/16 "2021-08-04T12:52:19Z")

</div>

> [@glv](#):
>
> 你好，
> 
> Processing Wiki 有一些故障排除技巧，包括这个：[https](https://github.com/processing/processing/wiki/Troubleshooting) :  
> [//github.com/processing/processing/wiki/Troubleshooting](https://github.com/processing/processing/wiki/Troubleshooting)
> 
> 另一个很好的资源：[https](https://forum.processing.org/two/discussion/8093/frequently-asked-questions) :  
> [//forum.processing.org/two/discussion/8093/frequently-asked-questions](https://forum.processing.org/two/discussion/8093/frequently-asked-questions)
> 
> `:)`

Thank you very much, I will read it carefully. 🙂
