Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.2 NumPy Arrays, Vectors, Matrices, and Shapes

This section helps you read NumPy arrays as vectors, matrices, or data tables, and helps you predict their shapes.
import numpy as np

u = np.array([3.0, 4.0])
A = np.array([[1.0, 2.0],
              [3.0, 4.0]])

u.shape
A.shape
Here u.shape is (2,), a one-dimensional array of length 2. The shape A.shape is (2, 2), a two-dimensional array with 2 rows and 2 columns.
A = np.array([[1, 2],
              [3, 4]], dtype=float)
Use dtype=float when converting integer or symbolic data for numerical linear algebra.
u = np.asarray([3, 4], dtype=float)
The command np.asarray treats existing array-like data as a NumPy array. In these notes it is used only to make short helper functions accept either lists or arrays.
v = np.asarray([1, 2, 3, 4], dtype=float).reshape(2, 2)
The method .reshape(2, 2) changes how entries are arranged into rows and columns when the total number of entries matches.

One-dimensional array.

np.array([3.0, 4.0])
Read as. A vector-like one-dimensional array.
Shape/return. Shape (2,).
Used for. Vectors in computations.

Matrix array.

np.array([[1.0, 2.0],
          [3.0, 4.0]])
Read as. A matrix.
Shape/return. Shape (2, 2).
Used for. Linear maps and data matrices.

Shape tuple.

A.shape
Read as. The dimensions of A.
Shape/return. A tuple.
Used for. Shape checks.

Floating-point entries.

dtype=float
Read as. Store entries as floating-point numerical values.
Shape/return. Numerical entries.
Used for. Numerical linear algebra.

Array conversion.

np.asarray(...)
Read as. Convert array-like input to a NumPy array.
Shape/return. A NumPy array.
Used for. Helper functions.

Reshape.

.reshape(m, n)
Read as. Arrange the same entries in a new shape.
Shape/return. Shape (m, n) if the number of entries matches.
Used for. Converting flat numerical output into a matrix shape.

Warning B.2.1. One-dimensional arrays are not column matrices.

The array np.array([3.0, 4.0]) is not a \(2\times 1\) matrix. It is a one-dimensional array of length 2. NumPy still allows it in expressions such as A @ u when the dimensions match.