Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.4 Elementwise Arithmetic Versus Linear Algebra

This section helps you read the difference between entry-by-entry arithmetic and linear-algebra operations.
u = np.array([1.0, 2.0])
v = np.array([3.0, 4.0])

u + v
2 * u
u * v      # entry-by-entry product
u**2       # entry-by-entry square
u @ v      # dot product
A = np.array([[1.0, 2.0],
              [3.0, 4.0]])

A @ u      # matrix-vector product
A.T        # transpose
A.T @ u
Code pattern Read as
u * v entry-by-entry product
u @ v dot product
A @ u matrix-vector product
A @ B matrix product

Vector arithmetic.

u + v, 2 * u, u**2
Read as. Vector sum, scalar multiple, and entry-by-entry square.
Shape/return. Vectors with matching shape.
Used for. Vector arithmetic and coordinatewise operations.

Transpose.

Read as. The transpose of A.
Shape/return. A matrix with rows and columns switched.
Used for. Residual checks and shape changes.

Quadratic form.

h @ H @ h
Read as. The scalar \(\mathbf h^T H\mathbf h\text{.}\)
Shape/return. A scalar.
Used for. Hessian quadratic forms and the quadratic part of a Taylor polynomial.
Watch for. NumPy evaluates this left to right, but for one-dimensional h this reads as \(\mathbf h^T H\mathbf h\text{.}\)

Sampled polynomial features.

xs**2, xs**3, xx*yy
Read as. Entry-by-entry powers or products of sampled coordinate arrays.
Shape/return. Arrays with the same shape as the sampled input arrays.
Used for. Polynomial feature columns in design matrices.

Warning B.4.1. Entrywise multiplication is not matrix multiplication.

The symbol * is entry-by-entry multiplication. The symbol @ is the dot product, matrix-vector product, or matrix-matrix product.
Unit 1 uses u @ v, K @ q, alpha @ V, and Y = A @ X. These are linear-algebra operations, not entry-by-entry multiplication.

Checkpoint B.4.2. Check Yourself: * versus @.

Let u = np.array([1, 2]) and v = np.array([3, 4]). Which expression computes the dot product, u * v or u @ v? What does the other expression compute?