Vectors: Vector calculus in Python
Selection of components, and assignment of values
Selection of components and subvectors You can select components of vectors in different ways. We give a few examples showing that indexing starts at 0 and that there a smart methods to create some vectors.
>>> v = np.arange(6,11); v
array([ 6, 7, 8, 9, 10])
>>> v[1] # a single element (2nd component)
7
>>> np.array((v[1], v[3])) # several components
array([7, 9])
>>>> v[1:4] # a subvector
array([7, 8, 9])
>>> v[1:] # everything except the first component
array([ 7, 8, 9, 10])
>>> v[:-1] # everything except the last component
array([6, 7, 8, 9])
>>> v[:,np.newaxis] # everything as column vector
array([[ 6],
[ 7],
[ 8],
[ 9],
[10]])
>>> v = v.reshape(np.size(v),1); v # everything as column vector
array([[ 6],
[ 7],
[ 8],
[ 9],
[10]])
Selection via logical expressions You can also use logical indexing (with values true and false) to select components of vectors. You need relational operators for this, such as the ones in the table below. Besides logical indexing you can also use the where
instruction to find suitable indices for a logical expression.
== | equal to | != | not equal to |
< | less than | > | greater than |
<= | less than or equal to | >= | greater than or equal to |
>>> v = np.arange(5,11); print(v)
[ 5 6 7 8 9 10]
>>> # vector values true/false if the condition is indeed/not met:
>>> lv = v>8; print(lv)
[False False False False True True]
>>> v[lv] # selection of components
array([ 9, 10])
>>> i = np.where(v<8); i # selection of indices via where command
(array([0, 1, 2], dtype=int64),)
>>> v[i] # selection of components
array([5, 6, 7])
Assignment Components to which you refer can also be assigned new values.
>>> v = np.arange(5,11); v[1] = 4; v # assign the first component the value 4 array([ 5, 4, 7, 8, 9, 10])
>>> v[:2] = 5; v # assign the first two components the value 5 array([ 5, 5, 7, 8, 9, 10]) >> np.delete(v,1) # remove the second component array([ 5, 7, 8, 9, 10])
>>> v[:] = 1; v # assign all components the value 1 array([1, 1, 1, 1, 1, 1])
By assignments you cannot change the structure. In the example below, we give the vector is an extra component via the append
function, but this is not done in-line, that is to say, the structure of the vector does not change (an assignment is required for this purpose). By the way, this is not a recommended approach. Pre-reserving ample space for components in a vector using the zero construction and then filling the data vector with values by assignments is a better way to collect data in Python experiments such as response times to stimuli.
>>> v = np.arange(5, 8); v % vector of length 3
>>> v = np.append(v,8); v
array([5, 6, 7, 8])