Vector operations II

4. Vector operations II#

Now that you have your vectors encoded in NumPy arrays, we can apply operations to them! As you’ll see below, NumPy arrays offer much more flexibility than built-in lists in Python.

Summary of commands#

In this exercise, we will demonstrate the following:

  • NumPy array operators, including addition +, multiplication *, and exponentiation **.

Element-wise operations#

We’ll define two vectors, \(x = \begin{bmatrix} 1 & -2 & 5 & 3 \end{bmatrix}\) and \(y = \begin{bmatrix} 4 & 1 & 0 & -1 \end{bmatrix}\). We’ll add and multiply \(x\) and \(y\) element by element, and then compute the squares of the elements of \(x\). In Python/NumPy, this is done in the ways you’d expect.

import numpy as np    # we do this every time
x = np.array([1, -2, 5, 3])
y = np.array([4, 1, 0, -1])

print("Addition:")
print(x + y)

print("Multiplication:")
z = x * y
print(z)

print("Squaring x:")
print(x ** 2)
Addition:
[ 5 -1  5  2]
Multiplication:
[ 4 -2  0 -3]
Squaring x:
[ 1  4 25  9]

Note

In MATLAB, you may be used to .* and ./ to perform element-wise multiplication and division. In NumPy, this is the default behavior.

Important

This is not what happens with lists in Python! Using the same operators could generate errors or incorrect behavior.

# create two lists
xl = [1, -2, 5, 3]
yl = [4, 1, 0, -1]
print(type(xl), xl)

# try adding two lists - what do you get?
zl = xl + yl
print(zl)

# try multiplying two lists - what do you get?
print(xl * yl)
<class 'list'> [1, -2, 5, 3]
[1, -2, 5, 3, 4, 1, 0, -1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 11
      8 print(zl)
     10 # try multiplying two lists - what do you get?
---> 11 print(xl * yl)

TypeError: can't multiply sequence by non-int of type 'list'

Yikes.