title: matlab indexing 3D array
body: <p>Suppose I construct the following 3D array</p>
  
  <pre><code>n = 3;
  A = zeros(n,n,n);
  A(1:n^3) = 1:n^3;
  </code></pre>
  
  <p>which gives</p>
  
  <pre><code>&gt;&gt; A
  
  A(:,:,1) =
  
   1     4     7
   2     5     8
   3     6     9
  
  A(:,:,2) =
  
  10    13    16
  11    14    17
  12    15    18
  
  A(:,:,3) =
  
  19    22    25
  20    23    26
  21    24    27
  </code></pre>
  
  <p>One can see how matlab indexes a 3D array from the above example. Suppose I would like to access (ii = 1, jj = 3, kk = 2) element of this array, which can be done by</p>
  
  <pre><code>&gt;&gt;A(1,3,2)
  
  ans =
  
  16
  </code></pre>
  
  <p>Alternatively, I can use the following form based on the matlab indexing rule demonstrated above</p>
  
  <pre><code>A(ii + (jj-1)*n + (kk-1)*n^2)
  </code></pre>
  
  <p>as an example, for ii = 1, jj = 3, kk = 2, I get</p>
  
  <pre><code>&gt;&gt;  A(1 + (3-1)*3 + (2-1)*3^2)
  
  ans =
  
  16
  </code></pre>
  
  <p>To illustrate the problem, I define the following 3D meshgrid (say for the purpose of index manupulations which is not relevant here):</p>
  
  <pre><code>[j1 j2 j3] = meshgrid(1:n);
  </code></pre>
  
  <p>If I am not wrong, common sense would expect that </p>
  
  <pre><code>A(j1 + (j2-1)*n +(j3-1)*n^2)
  </code></pre>
  
  <p>to give me the same matrix based on the above discussions, but I get</p>
  
  <pre><code>&gt;&gt; A(j1 + (j2-1)*3 +(j3-1)*3^2)
  
  ans(:,:,1) =
  
   1     2     3
   4     5     6
   7     8     9
  
  ans(:,:,2) =
  
  10    11    12
  13    14    15
  16    17    18
  
  ans(:,:,3) =
  
  19    20    21
  22    23    24
  25    26    27
  </code></pre>
  
  <p>From this I see that if you want to get the same 3D array you actually need to use</p>
  
  <pre><code>&gt;&gt; A(j2 + (j1-1)*3 +(j3-1)*3^2)
  </code></pre>
  
  <p>which is very strange to me. I am posting this issue here to see what other people think about this.</p>