4.2  Linear Algebra

NumPy provides robust support for linear algebra operations through its numpy.linalg module. This is essential for mechanics, where vectors and matrices are the primary language.

Vector Operations

Dot Product

The dot product is a fundamental operation for projections and calculating work.

import numpy as np

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

# Dot product
dot_prod = np.dot(a, b)
# OR using the @ operator
dot_prod_op = a @ b

print(f"Dot product: {dot_prod}")
Dot product: 32

Cross Product

The cross product is used for calculating moments and normal vectors.

# Cross product
cross_prod = np.cross(a, b)
print(f"Cross product: {cross_prod}")
Cross product: [-3  6 -3]

Norms

Calculating the magnitude (length) of a vector.

# L2 Norm (Euclidean length)
magnitude = np.linalg.norm(a)
print(f"Magnitude of a: {magnitude}")
Magnitude of a: 3.7416573867739413

Matrix Operations

Matrix Multiplication

It is crucial to distinguish between element-wise multiplication (*) and matrix multiplication (@ or np.matmul).

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

# Element-wise multiplication
print(f"Element-wise (A * B):\n{A * B}")

# Matrix multiplication
print(f"Matrix multiplication (A @ B):\n{A @ B}")
Element-wise (A * B):
[[ 5 12]
 [21 32]]
Matrix multiplication (A @ B):
[[19 22]
 [43 50]]

Determinants

The determinant is a scalar value that can be computed from the elements of a square matrix. It provides important information about the matrix, such as whether it is invertible.

# Calculate determinant
det_A = np.linalg.det(A)
print(f"Determinant of A: {det_A}")
Determinant of A: -2.0000000000000004

Solving Linear Systems

Solving systems of equations \(Ax = b\).

A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])

# Solve for x
x = np.linalg.solve(A, b)
print(f"Solution x: {x}")

# Verify solution
print(f"Check A@x: {A @ x}")
Solution x: [2. 3.]
Check A@x: [9. 8.]

Eigenvalues and Eigenvectors

Crucial for principal stress analysis, stability analysis, and vibrations.

# Define a symmetric matrix (e.g., stress tensor)
S = np.array([[10.0, 2.0], [2.0, 5.0]])

# Calculate eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(S)

print(f"Eigenvalues: {eigenvalues}")
print(f"Eigenvectors:\n{eigenvectors}")
Eigenvalues: [10.70156212  4.29843788]
Eigenvectors:
[[ 0.94362832 -0.33100694]
 [ 0.33100694  0.94362832]]

Rotations

Rotations in 3D space can be represented using rotation matrices.

theta = np.radians(45) # Convert degrees to radians
c, s = np.cos(theta), np.sin(theta)

# Rotation matrix around Z-axis
R_z = np.array([
    [c, -s, 0],
    [s,  c, 0],
    [0,  0, 1]
])

v = np.array([1, 0, 0])
v_rotated = R_z @ v
print(f"Rotated vector: {v_rotated}")
Rotated vector: [0.70710678 0.70710678 0.        ]