Shapes:
Let M to be the your n-dimensional array:
Reference image: https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png
- A shape of M (x,) means your array have x lines
- A shape of M (x, y) means your array have x lines and y columns
- A shape of M (x, y, z) means your array have x lines, y columns and z "layers"
If you want you can think of shapes as (lines, columns, layers,...), but things become complicated when you talk about 4-dimensional arrays or greater (maybe you could name them as stacks of blocks for 4-th dimension).
Anyway, a way better naming convention is the following:
M (axis 0, axis 1, axis 2, ..., axis n) as shown in the reference image.
To find the shape of array in python, simply write: M.shape
Slicing:
In array indexing, the comma separates the dimensions of array:
M [axis 0, axis 1, axis 2, ..., axis n]
For each axis you can have the following slice strucure:
[ start : stop : step ] where:
- start: first index for selected axis (included in the result)
- start = 0 is the default start index (does not need to be specified)
- stop: last index for selected axis (not included in the result)
- stop = len(axis) is the default end index (does not need to be specified)
- step: the step of traversing the selected axis:
- step = 0 is not allowed
- step = 1 is the default step (does not need to be specified)
- step = -1 means reverse traversing
- step = n means from n to n step
The following slicings are equivalent:
M [0:n+1:1], M [:] and M[::] according to default values.
Mixed together, now we can write ageneric slicing notation:
M [start-index-for-axis 0 : stop-index-for-axis 0 : step-for-axis 0,
start-index-for-axis 1 : stop-index-for-axis 1 : step-for-axis 1,
start-index-for-axis 2 : stop-index-for-axis 2 : step-for-axis 2,
...
start-index-for-axis n : stop-index-for-axis n : step-for-axis n],
Enough theory, let's see some examples:
We have M 2-dimensional array with (5, 5) shape:
M = np.arange(1, 26).reshape(5, 5)
print(M)
result:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]
print('Traverse the matrix from last line to first one (axis=0)', matrix[::-1], sep='\n')
result:
[[21 22 23 24 25]
[16 17 18 19 20]
[11 12 13 14 15]
[ 6 7 8 9 10]
[ 1 2 3 4 5]]
print('The 3 columns in the middle of the matrix (take all data from axis=0, and take a slice from axis=1):' , matrix[:, 1:4],sep='\n')
result:
[[ 2 3 4]
[ 7 8 9]
[12 13 14]
[17 18 19]
[22 23 24]]
Now, your slice: W [:, :, :, a], where a is an integer variable, can be interpreted as:
- M is a 4D array
- you take all from axis 0, axis 1 and axis 2
- you take just index a from axis 3
4D array can be imagined as stack/array of 3D blocks, and your slice means: take the a column from each matrix from each block, and ends up with a 3D array.