title: Vector Convolution - Calculating the Index of a Neighbour Element
body: <p>I am trying to implement a convolution method taking two vectors: an image; and a kernel. My problem is that i don't know how to calculate the index of the image neighbour element when I "slide" the kernel over the image vector. For example, with two identical vectors {0, 1, 2, 3, 4, 5, 6, 7, 8} I would like to achieve the following result:</p>
  
  <h2><a href="https://i.stack.imgur.com/t3lxy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t3lxy.jpg" alt="enter image description here"></a></h2>
  
  <p>My code so far is as follows:</p>
  
  <pre><code>public int[] convolve(int[] image, int[] kernel)
  {       
    int imageValue; 
    int kernelValue;
    int outputValue;
    int[] outputImage = new int[image.length()];
  
    // loop through image
    for(int i = 0; i &lt; image.length(); i++)
    {      
      outputValue = 0;
  
      // loop through kernel
      for(int j = 0; j &lt; kernel.length(); j++)
      {
        neighbour = ?;
  
        // discard out of bound neighbours 
        if (neighbour &gt;= 0 &amp;&amp; neighbour &lt; imageSize)
        {
          imageValue = image[neighbour];
          kernelValue = kernel[j];          
          outputValue += imageValue * kernelValue;
        }
      }
  
      output[i] = outputValue;
    }        
  
    return output;
  }
  </code></pre>