Home > Net >  Trouble understanding the function of : in array indexing? Python
Trouble understanding the function of : in array indexing? Python

Time:10-30

I have this line in the code:

next_J[v] = np.min(Q[v, :] J)

Where essentially Q is an matrix of size n x n and J is a vector of size n. What does Q[v, :] mean?

I tried to code this out but still do not understand what exactly it does.

CodePudding user response:

Q[v,:] is translated by the interpreter as Q.__getitem__((v, slice(None))

Note the (,) tuple syntax.

For a 2d array, this means select the v row. The slice selects all columns, and isn't actually needed in this context.

For a list this produces an error. alist[v] would work.

Q[v] J may not work fot lists, depending on what J is. is different for lists. The class of an object is important in understanding code.

The use of : in python indexing is basic. So is its use jn numpy indexing.

There's a lot more about using slicing with numpy arrays at https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding

  • Related