MATLAB ind2sub and Numpy unravel_index inconsistency
<p>Based on the <a href="http://stackoverflow.com/a/33072609">following answer</a>:</p>

<p>Using Octave, I get:</p>

<pre><code>&gt;&gt; [x, y, z] = ind2sub([27, 5, 58], 3766)
x =  13
y =  5
z =  28
</code></pre>

<p>Using Numpy, I get:</p>

<pre><code>&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; np.unravel_index(3765, (27, 5, 58))
(12, 4, 53)
</code></pre>

<p>Why, in Numpy, the <code>z</code> component is 58, when it should be 27 according to octave?</p>

<p>Well with MATLAB that follows column-major indexing, for <code>(x,y,z)</code> the elements are stored at <code>x</code>, then <code>y</code> and then <code>z</code>. With NumPy for <code>(x,y,z)</code> because of row-major indexing, it's the other way - <code>z</code>, <code>y</code> and then <code>x</code>. So, to replicate the same behavior in NumPy, you need to flip the grid shape for use with <code>np.unravel_index</code> and finally flip the output indices, like so -</p>

<pre><code>np.unravel_index(3765, (58, 5, 27))[::-1]
</code></pre>

<p>Sample run -</p>

<pre><code>In [18]: np.unravel_index(3765, (58, 5, 27))[::-1]
Out[18]: (12, 4, 27)
</code></pre>

python matlab numpy