python numpy vector math

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    In [2]: import numpy as np
    In [3]: a = np.array([4,2,7])
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    In [6]: b = a/np.linalg.norm(a)
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

python numpy vector math

Leave a Reply

Your email address will not be published. Required fields are marked *