Vector operations

In addition to being mathematical entities studied in linear algebra, Vectors are widely used in physics and engineering as a convenient way to represent physical quantities as displacement, velocity, acceleration, force, and so on. Accordingly, basic operations between vectors can be performed via Numpy/SciPy operations as follows:

Addition/subtraction

Addition/subtraction of vectors does not require any explicit loop to perform them. Let's take a look at addition of two vectors:

>>> vectorC = vectorA + vectorB
>>> vectorC

The output is shown as follows:

array([8, 8, 8, 8, 8, 8, 8])

Further, we perform subtraction on two vectors:

>>> vectorD = vectorB - vectorA
>>> vectorD

The output is shown as follows:

array([ 6,  4,  2,  0, -2, -4, -6])

Scalar/Dot product

Numpy has the built-in function dot to compute the scalar (dot) product between two vectors. We show you its use computing the dot product of vectorA and vectorB from the previous code snippet:

>>> dotProduct1 = numpy.dot(vectorA,vectorB)
>>> dotProduct1

The output is shown as follows:

84

Alternatively, to compute this product we could perform the element-wise product between the components of the vectors and then add the respective results. This is implemented in the following lines of code:

>>> dotProduct2 = (vectorA*vectorB).sum()
>>> dotProduct2

The output is shown as follows:

84

Cross/Vector product – on three-dimensional space vectors

First, two vectors in 3 dimensions are created before applying the built-in function from NumPy to compute the cross product between the vectors:

>>> vectorA = numpy.array([5, 6, 7])
>>> vectorB = numpy.array([7, 6, 5])
>>> crossProduct = numpy.cross(vectorA,vectorB)
>>> crossProduct

The output is shown as follows:

array([-12,  24, -12])

Further, we perform a cross operation of vectorB over vectorA:

>>> crossProduct = numpy.cross(vectorB,vectorA)
>>> crossProduct

The output is shown as follows:

array([ 12, -24,  12])

Notice that the last expression shows the expected result that vectorA cross vectorB is the negative of vectorB cross vectorA.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.212