ZhangZhihui's Blog  

1. numpy.dot() — Dot Product (Scalar or Matrix Multiplication)

Purpose:

Computes the dot product of two vectors, or does matrix multiplication if 2D arrays are involved.

📌 Behavior:

  • For 1D arrays (vectors): Returns a scalar (the inner product).

  • For 2D arrays: Equivalent to matrix multiplication.

  • For higher dimensions: It uses the last axis of a and second-to-last of b for computation.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

np.dot(a, b)  # 1*4 + 2*5 + 3*6 = 32

📌 Output: 32

 

import numpy as np

A = np.array([[1, 2],
              [3, 4]])

B = np.array([[5, 6],
              [7, 8]])

result = np.dot(A, B)
print(result)

What it does:

Performs matrix multiplication:

[[1*5 + 2*7, 1*6 + 2*8],
 [3*5 + 4*7, 3*6 + 4*8]]

✅ Output:

[[19 22]
 [43 50]]

 

2. numpy.cross() — Cross Product (Only for 3D or 2D vectors)

Purpose:

Computes the cross product, which results in a vector that is perpendicular to the input vectors (in 3D).

📌 Behavior:

  • Only makes sense for 3D or 2D vectors.

  • Result is a vector (not a scalar).

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

np.cross(a, b)  # [2*6 - 3*5, 3*4 - 1*6, 1*5 - 2*4]

📌 Output: [-3, 6, -3]

 

When used on 2D arrays, np.cross() computes the cross product row-wise, treating each row as a 3D vector. If the input vectors are 2D (length 2), it assumes z=0 and returns a scalar for each pair.

import numpy as np

A = np.array([[1, 2],
              [3, 4]])

B = np.array([[5, 6],
              [7, 8]])

result = np.cross(A, B)
print(result)

🔍 What it does:

For 2D vectors [x1, y1] and [x2, y2], the 2D cross product is:

x1*y2 - x2*y1

So:

  • Row 1: 1*6 - 5*2 = 6 - 10 = -4

  • Row 2: 3*8 - 7*4 = 24 - 28 = -4

✅ Output:

[-4 -4]

 

import numpy as np

A = np.array([[1, 0, 0],
              [0, 1, 0]])

B = np.array([[0, 1, 0],
              [0, 0, 1]])

result = np.cross(A, B)
print(result)

Explanation:

Cross product between 3D vectors:

  • [1, 0, 0] × [0, 1, 0] = [0, 0, 1]

  • [0, 1, 0] × [0, 0, 1] = [1, 0, 0]

✅ Output:

[[0 0 1]
 [1 0 0]]

Each row of the result is the cross product of corresponding rows in A and B.

 

Summary Table:

FunctionOperation TypeInputOutputTypical Use
numpy.dot() Dot product Vectors/Matrices Scalar or Matrix Projections, similarity
numpy.cross() Cross product 2D/3D Vectors Vector Geometry, perpendicular vectors

✅ Summary Table:

FunctionInput (2D arrays)Output TypeMeaning
np.dot(A, B) 2D matrices 2D matrix Matrix multiplication
np.cross(A, B) 2D vectors row-wise 1D array of scalars Cross product (area of parallelogram in 2D)

 

posted on 2025-07-01 08:28  ZhangZhihuiAAA  阅读(61)  评论(0)    收藏  举报