Zero-based indexing

In math we use 1-based indexing, but in many programming languages including Python, we use 0-based indexing.

For example, a three dimensional vector $\vec{v} \in \mathbb{R}^3$ are denoted as $(v_1,v_2,v_3)$ in components form.

In Python a vector vec can be denoted as a list (or a Matrix), and its three components will be vec[0], vec[1], and vec[2]. The variable we to index the components is assumed to start at zero, not one.


In [1]:
from sympy import Matrix, symbols
a, b, c = symbols('a b c')

vec = Matrix([a,b,c])
vec


Out[1]:
Matrix([
[a],
[b],
[c]])

In [2]:
vec[0]


Out[2]:
a

In [3]:
vec[1]


Out[3]:
b

In [4]:
vec[2]


Out[4]:
c

In [5]:
# trying to access vec[3] leads to an error, 
# since a 3 in 0-based indexing is accessing a fourth component which doesn't exist
vec[3]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-ad6368f205ef> in <module>()
      1 # trying to access vec[3] leads to an error,
      2 # since a 3 in 0-based indexing is accessing a fourth component which doesn't exist
----> 3 vec[3]

/Users/ivan/Projects/Minireference/content/noBSLAnotebooks/pydev/lib/python3.5/site-packages/sympy/matrices/dense.py in __getitem__(self, key)
     94             if isinstance(key, slice):
     95                 return self._mat[key]
---> 96             return self._mat[a2idx(key)]
     97 
     98     def __setitem__(self, key, value):

IndexError: list index out of range

Ranges


In [6]:
# a list of five numbers
list(range(0,5))
# Note the second argument of the function range specifies
#      the first number not to be included in the range...


Out[6]:
[0, 1, 2, 3, 4]

In [ ]:

SymPy shorthand for ranges


In [7]:
# consider a 2x3 matrix
A = Matrix([
        [1,2,3],
        [4,5,6]])
A


Out[7]:
Matrix([
[1, 2, 3],
[4, 5, 6]])

In [14]:
# can access individual entry on row i, col j using A[i-1,j-1]
print('top left =',    A[0,0], '    top right =', A[0,2])
print('bottom left =', A[1,0], ' bottom right =', A[1,2])


top left = 1     top right = 3
bottom left = 4  bottom right = 6

In [9]:
# can access entire colum j using A[:,j-1]
A[:,0]


Out[9]:
Matrix([
[1],
[4]])

In [ ]:
# can access entire row i using A[i-1,:]
A[0,:]

In [ ]:
# can access left 2x2 submatrix using i:j shorhand range notation
A[0:2,0:2]

In [ ]:
# the above notation is MATLAB-like syntax sugar that translates to
A[range(0,2),range(0,2)]

In [ ]: