SoFunction
Updated on 2024-11-13

Several matrix multiplication formulas for python in detail

1. Same as the definition of matrix multiplication in linear algebra: ()

(A, B): for two-dimensional matrices, compute the matrix product in the true sense, as defined for matrix multiplication in linear algebra. For one-dimensional matrices, compute the inner product of the two. See the following Python code:

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = ([[1, 2, 3], [4, 5, 6]])
# 2-D array: 3 x 2
two_dim_matrix_two = ([[1, 2], [3, 4], [5, 6]])

two_multi_res = (two_dim_matrix_one, two_dim_matrix_two)
print('two_multi_res: %s' %(two_multi_res))

# 1-D array
one_dim_vec_one = ([1, 2, 3])
one_dim_vec_two = ([4, 5, 6])
one_result_res = (one_dim_vec_one, one_dim_vec_two)
print('one_result_res: %s' %(one_result_res))

The results are as follows:

two_multi_res: [[22 28]
 [49 64]]
one_result_res: 32

2. Multiplication of corresponding elements element-wise product: (), or *

In Python, there are 2 ways to implement multiplication of corresponding elements, one is () and the other is *. See the following Python code:

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = ([[1, 2, 3], [4, 5, 6]])
another_two_dim_matrix_one = ([[7, 8, 9], [4, 7, 1]])

# Multiply corresponding elements element-wise product
element_wise = two_dim_matrix_one * another_two_dim_matrix_one
print('element wise product: %s' %(element_wise))

# Multiply corresponding elements element-wise product
element_wise_2 = (two_dim_matrix_one, another_two_dim_matrix_one)
print('element wise product: %s' % (element_wise_2))

The results are as follows:

element wise product: [[ 7 16 27]
 [16 35 6]]
element wise product: [[ 7 16 27]
 [16 35 6]]

This is the whole content of this article.