NumPy matrix not indexing range correctly [0,0,0,5:53].shape = 43
<p>I have a rather large numpy matrix, and I'm thinking since it is so large this is happening. It has to be some sort of pointer issue.</p>

<p>Anyways, I have the following matrix </p>

<pre><code>(Pdb) input_4d_volume.shape
(26010, 48, 48, 48)
</code></pre>

<p>When I index like the following, no problem: </p>

<pre><code>(Pdb) input_4d_volume[0,0,0,0:48].shape[0]
48
</code></pre>

<p>But when I try to do a range, the max always max's out at <code>48</code></p>

<p>For example, take these two cases:</p>

<pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0]
47
(Pdb) input_4d_volume[0,0,0,10:10+48].shape[0]
38
</code></pre>

<p>The expected outputs should be:</p>

<pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0]
48
(Pdb) input_4d_volume[0,0,0,10:10+48].shape[0]
38
</code></pre>

<p>Since, <code>(1+48)-1 = 48</code> and <code>(10+48)-10 = 48</code> (see below examples as proof)</p>

<p>As proof this works, I have another matrix that works perfectly fine</p>

<pre><code>(Pdb) entire_volume.shape
(99, 396, 396)
(Pdb) entire_volume[0,0,0:100].shape[0]
100
(Pdb) entire_volume[0,0,10:10+100].shape[0]
100
</code></pre>

<p>Is this because <code>input_4d_volume</code> is too large?</p>

<p>Python will let you index up to a number larger than the length of the object. For example,</p>

<pre><code>import numpy as np
a = np.arange(0, 10)
a[5:100]
# array([5, 6, 7, 8, 9])
</code></pre>

<p>If your 4-D input array is of shape (26010, 48, 48, 48), and you are slicing on the 4th dimension, you cannot end up with an 1D array large than that dimension's size. For example,</p>

<pre><code>a = np.zeros((100,30,30,30))
a[0, 0, 0, 0:5].shape
# (5L,)

a[0, 0, 0, 0:32].shape
# (30L,)
</code></pre>

<p>In your proof that it works example, you are taking a slice on dimension three of indices 10 to 109 with <code>entire_volume[0,0,10:10+100].shape[0]</code>. These are within the dimension's size of 396, so you get what you expect.</p>

<p>If you instead did <code>entire_volume[0,0,390:390+100].shape[0]</code>, the shape of the array returned is the same as if you sliced with <code>entire_volume[0,0,390:396].shape[0]</code>. Python lets you go above the max, but it can't return data that doesn't exist.</p>

python numpy