Skip to content

NumPy - Matrix Library

NumPy includes a numpy.matlib module and a numpy.matrix class. These were primarily designed for users familiar with MATLAB, offering specialized matrix operations. However, in modern NumPy, using standard numpy.ndarray objects is strongly recommended for all array operations, including linear algebra. Standard arrays are more general (supporting N dimensions beyond 2) and consistent with the rest of the NumPy ecosystem.

This section describes the numpy.matlib functions for historical context and completeness, but you should generally prefer their np.ndarray equivalents.

The matlib.empty() function returns a new, uninitialized matrix. Its contents are unpredictable (random data from memory) and it’s rarely used in practice. Use np.zeros or np.ones for initialized arrays.

numpy.matlib.empty(shape, dtype=float, order='C')

Parameters:

ParameterDescription
shapeTuple of ints defining the shape (rows, columns) of the new matrix.
dtypeOptional data type.
order’C’ (row-major) or ‘F’ (column-major) memory layout.

Demonstrates matlib.empty. Note the arbitrary initial values.

import numpy.matlib
import numpy as np
# Creates a 2x2 matrix with uninitialized values
mat = np.matlib.empty((2, 2))
print(mat)
# Modern equivalent (initialized with zeros):
arr = np.zeros((2, 2))
print('\nEquivalent ndarray using np.zeros:')
print(arr)

Potential Output (values in the first matrix will vary):

[[6.95335581e-310 6.95335581e-310]
[6.95335581e-310 6.95335581e-310]]
Equivalent ndarray using np.zeros:
[[0. 0.]
[0. 0.]]

Returns a matrix filled with zeros. The modern equivalent is np.zeros().

Example:

import numpy.matlib
import numpy as np
print(np.matlib.zeros((2, 2)))
# Modern equivalent:
print('\nEquivalent ndarray using np.zeros:')
print(np.zeros((2, 2)))

Output:

[[0. 0.]
[0. 0.]]
Equivalent ndarray using np.zeros:
[[0. 0.]
[0. 0.]]

Returns a matrix filled with ones. The modern equivalent is np.ones().

Example:

import numpy.matlib
import numpy as np
print(np.matlib.ones((2, 2)))
# Modern equivalent:
print('\nEquivalent ndarray using np.ones:')
print(np.ones((2, 2)))

Output:

[[1. 1.]
[1. 1.]]
Equivalent ndarray using np.ones:
[[1. 1.]
[1. 1.]]

Returns a matrix with ones on a specified diagonal (k) and zeros elsewhere. The modern equivalent is np.eye().

numpy.matlib.eye(n, M=None, k=0, dtype=float)

Parameters:

ParameterDescription
nNumber of rows.
MNumber of columns (defaults to n).
kIndex of the diagonal (0 = main, positive = upper, negative = lower).
dtypeData type.
import numpy.matlib
import numpy as np
print(np.matlib.eye(n=3, M=4, k=0, dtype=float))
# Modern equivalent:
print('\nEquivalent ndarray using np.eye:')
print(np.eye(N=3, M=4, k=0, dtype=float))

Output:

[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
Equivalent ndarray using np.eye:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]

Returns a square identity matrix (ones on the main diagonal, zeros elsewhere). The modern equivalent is np.identity().

Example:

import numpy.matlib
import numpy as np
print(np.matlib.identity(5, dtype=float))
# Modern equivalent:
print('\nEquivalent ndarray using np.identity:')
print(np.identity(5, dtype=float))

Output:

[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
Equivalent ndarray using np.identity:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]

Returns a matrix of a given shape filled with random values from a uniform distribution [0.0, 1.0). For modern, reproducible random number generation, use numpy.random.Generator.random().

import numpy.matlib
import numpy as np
# Using matlib (older style)
print(np.matlib.rand(3, 3))
# Modern equivalent using default_rng
rng = np.random.default_rng() # Create a random number generator
print('\nEquivalent ndarray using rng.random:')
print(rng.random((3, 3)))

Potential Output (values will vary):

[[0.78917483 0.04406774 0.3003236 ]
[0.47106717 0.80335701 0.94395156]
[0.68432136 0.46957171 0.1159008 ]]
Equivalent ndarray using rng.random:
[[0.61316899 0.98466865 0.86255636]
[0.84031023 0.77267917 0.9284747 ]
[0.56171617 0.94888112 0.31174664]]

Key Difference: np.matrix objects are strictly 2-dimensional, whereas np.ndarray objects can have any number of dimensions. np.matrix also overrides multiplication (*) to mean matrix multiplication, while * means element-wise multiplication for np.ndarray (use @ or np.matmul() for matrix multiplication with ndarrays).

Converting between np.matrix (legacy) and np.ndarray (preferred).

Creating a matrix (legacy way):

import numpy as np
# Create a matrix (legacy)
i = np.matrix([[1, 2], [3, 4]]) # Note the use of nested lists
print("Legacy np.matrix:")
print(i)
print(type(i))

Output:

Legacy np.matrix:
[[1 2]
[3 4]]
<class 'numpy.matrix'>

Converting matrix to ndarray:

import numpy as np
i = np.matrix([[1, 2], [3, 4]])
# Convert matrix to ndarray (preferred type)
j = np.asarray(i)
print("Converted to np.ndarray:")
print(j)
print(type(j))

Output:

Converted to np.ndarray:
[[1 2]
[3 4]]
<class 'numpy.ndarray'>

Converting ndarray back to matrix (rarely needed):

import numpy as np
j = np.array([[1, 2], [3, 4]]) # Start with an ndarray
# Convert ndarray to matrix (legacy)
k = np.asmatrix(j)
print("Converted back to np.matrix:")
print(k)
print(type(k))

Output:

Converted back to np.matrix:
[[1 2]
[3 4]]
<class 'numpy.matrix'>