SoFunction
Updated on 2024-12-13

Example of a NumPy Matrix Multiplication Implementation

The several types of matrix multiplication supported by NumPy are also important.

Element level multiplication

You have already seen some element-wise multiplication. You can do this using the multiply function or the * operator. Recall that it looks like this:

m = ([[1,2,3],[4,5,6]])
m
# The following results are displayed:
# array([[1, 2, 3],
#  [4, 5, 6]])

n = m * 0.25
n
# The following results are displayed:
# array([[ 0.25, 0.5 , 0.75],
#  [ 1. , 1.25, 1.5 ]])

m * n
# The following results are displayed:
# array([[ 0.25, 1. , 2.25],
#  [ 4. , 6.25, 9. ]])

(m, n) # Equivalent to m * n
# The following results are displayed:
# array([[ 0.25, 1. , 2.25],
#  [ 4. , 6.25, 9. ]])

matrix product (math.)

To get the matrix product, you can use NumPy's matmul function.

If you have compatible shapes, it's as simple as this:

a = ([[1,2,3,4],[5,6,7,8]])
a
# The following results are displayed:
# array([[1, 2, 3, 4],
#  [5, 6, 7, 8]])

# The following results are displayed:
# (2, 4)

b = ([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
b
# The following results are displayed:
# array([[ 1, 2, 3],
#  [ 4, 5, 6],
#  [ 7, 8, 9],
#  [10, 11, 12]])

# The following results are displayed:
# (4, 3)

c = (a, b)
c
# The following results are displayed:
# array([[ 70, 80, 90],
#  [158, 184, 210]])

# The following results are displayed:
# (2, 3)

If your matrix has an incompatible shape, the following error occurs:

(b, a)
# The following error is displayed:
# ValueError: shapes (4,3) and (2,4) not aligned: 3 (dim 1) != 2 (dim 0)

NumPy's dot function

Sometimes you may see NumPy's dot function where you thought you'd use the matmul function. It turns out that if the matrix is two-dimensional, the dot and matmul functions give the same result.

So these two results are equivalent:

a = ([[1,2],[3,4]])
a
# The following results are displayed:
# array([[1, 2],
#  [3, 4]])

(a,a)
# The following results are displayed:
# array([[ 7, 10],
#  [15, 22]])

(a) # you can call you can call `dot` on `ndarray` directly
# The following results are displayed:
# array([[ 7, 10],
#  [15, 22]])

(a,a)
# array([[ 7, 10],
#  [15, 22]])

While both functions return the same results for two-dimensional data, you should choose carefully when using them for other data shapes. You can learn more about their differences and find links to other NumPy functions in the matmul and dot documentation.

To this point this article on the implementation of NumPy matrix multiplication example of the article is introduced to this, more related to NumPy matrix multiplication content please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!