title: 3D template matching using Cross Correlation in Matlab
body: <p>Here is a minimal example of what i try to do:  </p>
  
  <p>Create 3D matrix</p>
  
  <pre><code>a(:,:,1)=[
      1 2 3 4 1;
      2 3 7 1 4;
      3 7 6 0 9;
      0 3 2 8 1;
      1 4 3 1 1]
  
  a(:,:,2)=[
      1 7 3 4 2;
      2 9 2 3 1;
      1 4 7 7 0;
      1 2 3 4 1;
      0 9 3 3 9]
  
  a(:,:,3)=[
      9 4 0 3 5;
      1 2 3 4 1;
      2 0 2 3 1;
      1 4 2 1 1;
      2 5 7 8 1]
  
  a(:,:,4)=[
      2 3 5 2 0
      0 0 0 0 8
      5 2 7 9 8
      2 4 1 1 0
      6 3 8 7 9]
  
  a(:,:,5)=[
      3 5 1 4 6;
      3 2 8 0 0;
      0 2 1 0 4;
      5 4 5 5 6;
      9 5 9 9 5]
  </code></pre>
  
  <p>Create 3D template  </p>
  
  <pre><code>b(:,:,1)=[
      9 4 0;
      1 2 3;
      2 0 2]
  
  b(:,:,2)=[
      2 3 5;
      0 0 0;
      5 2 7]
  
  b(:,:,3)=[
      3 5 1;
      3 2 8;
      0 2 1]
  </code></pre>
  
  <p>Calculate Cross Correlation (<a href="https://stackoverflow.com/questions/12309509/3d-cross-correlation-in-matlab">3D cross-correlation in matlab</a>). I think Cross Correlation is the same as convolution with the flipped template. Is that correct?</p>
  
  <pre><code>c=convn(a,b(end:-1:1,end:-1:1,end:-1:1));
  </code></pre>
  
  <p>Find subscripts of best matching</p>
  
  <pre><code>[x y z] = ind2sub(size(c),find(c==max(c(:))));
  x=x-(size(b, 1) - 1)/2
  y=y-(size(b, 2) - 1)/2
  z=z-(size(b, 3) - 1)/2
  </code></pre>
  
  <p>I read that one has to subtract the half of the template size of the final coordinates but I don't have the link of the page with this information anymore. However, I think if one wouldn't do that returned coordinates are not the one of where the center of the template would be but on a corner of the template.</p>
  
  <p>As result of my example I expect: <code>x=2</code>, <code>y=2</code>, <code>z=4</code>. Matlab tells me it's <code>x=4</code>, <code>y=4</code>, <code>z=4</code>. However, when changing the template to</p>
  
  <pre><code>b(:,:,1)=[
      9 2 3;  
      4 7 7;
      2 3 4]
  
  b(:,:,2)=[
      2 3 4;
      0 2 3;
      4 2 1]
  
  b(:,:,3)=[
      0 0 0;
      2 7 9;
      4 1 1]
  </code></pre>
  
  <p>I get the correct result <code>(x=3, y=3, z=3)</code>.  </p>
  
  <p>What do I have to change to get always the correct result?  </p>