title: Looping through two matrices in java
body: <p>I am quite a newbie in java and programming in general and I have a project for text recognition from images for Android. I am working in Android Studio and currently I have two matrices - one with values for source image taken from device gallery and one with values for template image. The values in matrices are basically the colors of pixels, working in grayscale, devided into 6 intervals: color value of 255-214 equals 0, color value of 172-213 equals 0.2, color value of 129-171 equals 0.4 etc.</p>
  
  <p>I need to go line by line in both of the matrices and do some countings with them - take first value in first line of source matrix and first value in first line of template matrix and use it in formula:</p>
  
  <pre><code>nIntensity = 1 - abs(template_value - source_value)
  </code></pre>
  
  <p>and do this for all the values in one line, then do sum of these values and go to second line and do the same (resulting in an array of x nIntensity values for x matrix lines). What I tried at first was using nested loops, but I kinda overdid it with them:</p>
  
  <pre><code>for(int sRow = 0; sRow &lt; sourceMatrix.length; sRow++) {
      for(int sColumn = 0; sColumn &lt; 1; sColumn++) {
          for(int pRow = 0; pRow &lt; patternMatrix.length; pRow++) {
              for(int pColumn = 0; pColumn &lt; 1; pColumn++) {
                  nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));}}}}
  </code></pre>
  
  <p>which resulted in too high values for the nIntensity varriable - with 56 values equal to 1.0 in line for both sourceMatrix and patternMatrix I should get the result of number 56, instead I got 3192, implying it goes too many times through all the loops. With the <code>sColumn &lt; 1</code> and <code>pColumn &lt; 1</code> I tried to achieve going simple from the start and taking just the first line of both the matrices, before I dig deeper in it and work with multiple lines.</p>
  
  <p>After doing some research, I tried to make it quite simple with code:</p>
  
  <pre><code>for(int sRow = 0; sRow &lt; sourceMatrix.length; sRow++) {
      for (int sColumn = 0; sColumn &lt; 1; sColumn++) {
           nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
           System.out.println("Result: " + nIntensity);}}
  </code></pre>
  
  <p>which when I print the results after every loop actually gets to result 56, however crashes with the exception</p>
  
  <blockquote>
    <p>Caused by: java.lang.ArrayIndexOutOfBoundsException: length=56; index=56</p>
  </blockquote>