Multiplication of 2d arrays in Python

Multiplication of 2D arrays in Python involves performing matrix multiplication or element-wise multiplication, depending on the context. Let’s cover both scenarios:

1. Matrix Multiplication (Dot Product)

Matrix multiplication involves multiplying rows of the first matrix with columns of the second matrix to produce a new matrix. In Python, you can use numpy for efficient matrix operations.

Theory:

If you have two matrices A (m x n) and B (n x p), the resulting matrix C (m x p) is calculated as:

Cij=∑k=1nAik×BkjC_{ij} = \sum_{k=1}^{n} A_{ik} \times B_{kj}

2. Element-wise Multiplication

Element-wise multiplication multiplies corresponding elements of two matrices with the same dimensions.

Theory:

For two matrices A and B of the same shape, the element-wise multiplication C is calculated as:

Cij=Aij×BijC_{ij} = A_{ij} \times B_{ij}

  • Matrix Multiplication:
    • Involves rows of the first matrix multiplied by columns of the second.
    • Done using numpy.dot() function or .dot() method.
  • Element-wise Multiplication:
    • Multiplies corresponding elements of two matrices.
    • Performed using the * operator in Python (with NumPy arrays).

Matrix multiplication is fundamental in linear algebra and is used in various mathematical and scientific computations, while element-wise multiplication is useful when operations are required on corresponding elements of matrices. NumPy provides efficient implementations for both operations in Python.

Use the np.matmul(a, b) function that takes two NumPy arrays as input and returns the result of the multiplication of both arrays. The arrays must be compatible in shape.

import numpy as np

# Define two matrices
A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])

# Matrix multiplication
C = np.dot(A, B)
# Or equivalently: C = A.dot(B)

print("Matrix Multiplication (Dot Product):")
print(C)

 

output:
Matrix Multiplication (Dot Product):
[[19 22]
[43 50]]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top