Common Uses

NumPy

Matrix Multiplication / Manipulation

The following code sample shows how to create matrices, which look like arrays in Python.

# Import numpy and alias it as np
import numpy as np

# matrix_A looks like the following (row-major)
# | 100   200 |
# | 500   600 |
matrix_A = np.array( [[100, 200], [500, 600]] )

# matrix_B looks like the following (row-major)
# | 0.5   1.0 |
# | 1.0   0.5 |
matrix_B = np.array( [[0.5, 1.0], [1.0, 0.5]] )

With numpy, we can use element-wise multiplication OR matrix-wise multiplication. The typical multiplication operator * will go element-by-element and multiply each element and return the product. See the example below.

# Import numpy and alias it as np
import numpy as np

# We can multiply these as simply arrays of values.
# The elementwise multiplication is performed via the
# multiplication operator (*).
elementWise = matrix_A * matrix_B

# The operation above is equivalent to the following:
elementWise = [
        [ matrix_A[0][0] * matrix_B[0][0], matrix_A[0][1] * matrix_B[0][1] ],
        [ matrix_A[1][0] * matrix_B[1][0], matrix_A[1][1] * matrix_B[1][1] ]
        ]

# We can also do typical matrix muliplication
matrixWise = matrix_A @ matrix_B
# Don't think of @ as the 'at' operator. Instead, think of it as the
# numpy programmers ran out of other operators, and @ looks the most similar
# to *.