I've read documentation several times about np.indices() but I can't seem to grasp what is it about. I've used it numerous times on things to see what it does, but I still can't really get it. Maybe the thing is I'm a beginner in programming so I can't understand the idea behind the words describing it. In addition I'm not a native English speaker (though I have no problems with it). I would be very grateful for kind of easier explanation, possibly on some example. Thanks.
Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices. NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
What Makes NumPy So Good? NumPy has a syntax which is simultaneously compact, powerful and expressive. It allows users to manage data in vectors, matrices and higher dimensional arrays.
Suppose you have a matrix M whose (i,j)-th element equals
M_ij = 2*i + 3*j
One way to define this matrix would be
i, j = np.indices((2,3)) M = 2*i + 3*j
which yields
array([[0, 3, 6], [2, 5, 8]])
In other words, np.indices
returns arrays which can be used as indices. The elements in i
indicate the row index:
In [12]: i Out[12]: array([[0, 0, 0], [1, 1, 1]])
The elements in j
indicate the column index:
In [13]: j Out[13]: array([[0, 1, 2], [0, 1, 2]])
Step 1: Let's create a 2x2 grid
ids = np.indices((2,2))
Step 2: Now let's unpack the i,j
indices
i, j = ids
These are the indices i,j
:
print(i) [[0 0] [1 1]] print(j) [[0 1] [0 1]]
Step 3: Understand what i,j
represent
The easy way to think of it is to make pairs as (i0,j0), (i1,j1), (i2,j2), (i3,j3)
i.e. match each element of i
with the corresponding element of j
.
So we get: (0,0), (0,1), (1,0), (1,1)
.
These are exactly the indices of a 2x2 grid:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With