py4u blog

Mastering `numpy.asmatrix()` in Python: A Comprehensive Guide

NumPy is the cornerstone of numerical computing in Python, enabling efficient manipulation of multi-dimensional arrays and matrices. The numpy.asmatrix() function plays a crucial role in converting input data (e.g., lists, arrays) into a numpy.matrix object—a specialized subclass of ndarray optimized for linear algebra operations. While the matrix class is considered legacy (modern NumPy recommends ndarray with @ for matrix multiplication), asmatrix() remains relevant for legacy codebases and specific compatibility needs.

2026-10

Table of Contents#

Syntax and Parameters#

The numpy.asmatrix() function has the following syntax:

numpy.asmatrix(data, dtype=None)
  • data: The input data to be converted to a matrix. This can be a list, tuple, ndarray, or another matrix.
  • dtype (optional): The data type of the resulting matrix. If not specified, the data type is inferred from data.

How numpy.asmatrix() Works#

numpy.asmatrix() converts the input data into a numpy.matrix object. Key behaviors:

  1. Data Sharing vs. Copying:

    • If data is already a matrix, asmatrix() returns it (or a view) without copying.
    • If data is an ndarray, asmatrix() creates a matrix that shares data with the original array (modifying the matrix modifies the array, and vice versa).
    • If data is a list (or other non-array/non-matrix type), asmatrix() converts it to an ndarray first, then to a matrix (copying the data).
  2. 2D Requirement:

    • matrix objects are always 2-dimensional. If data is 1-dimensional (e.g., a list [1, 2, 3]), asmatrix() reshapes it into a row matrix (shape (1, n)).

Example Usage#

Converting a List to Matrix#

import numpy as np
 
# Convert a list of lists to a matrix
list_data = [[1, 2], [3, 4]]
matrix_from_list = np.asmatrix(list_data)
 
print("Matrix from list:")
print(matrix_from_list)
print("Type:", type(matrix_from_list))

Output:

Matrix from list:
[[1 2]
 [3 4]]
Type: <class 'numpy.matrix'>

Converting a NumPy Array to Matrix#

# Convert a NumPy array to a matrix (data sharing example)
array_data = np.array([[5, 6], [7, 8]])
matrix_from_array = np.asmatrix(array_data)
 
print("\nMatrix from array:")
print(matrix_from_array)
 
# Modify the matrix and check data sharing
matrix_from_array[0, 0] = 99
print("\nModified matrix:")
print(matrix_from_array)
print("Original array (modified due to data sharing):")
print(array_data)

Output:

Matrix from array:
[[5 6]
 [7 8]]

Modified matrix:
[[99  6]
 [ 7  8]]
Original array (modified due to data sharing):
[[99  6]
 [ 7  8]]

Handling Nested Lists and Multi-Dimensional Data#

# Convert a nested list (3x2) to a matrix
nested_list = [[1, 2], [3, 4], [5, 6]]
matrix_nested = np.asmatrix(nested_list)
 
print("\nMatrix from nested list:")
print(matrix_nested)
print("Shape:", matrix_nested.shape)
 
# Convert a 1D array to a matrix (reshaped to 2D)
one_d_array = np.array([10, 20, 30])
matrix_1d = np.asmatrix(one_d_array)
 
print("\nMatrix from 1D array (reshaped to 2D):")
print(matrix_1d)
print("Shape:", matrix_1d.shape)

Output:

Matrix from nested list:
[[1 2]
 [3 4]
 [5 6]]
Shape: (3, 2)

Matrix from 1D array (reshaped to 2D):
[[10 20 30]]
Shape: (1, 3)

Common Practices#

  1. Legacy Code Integration: Use asmatrix() to convert data to matrix type when working with older codebases that rely on matrix objects (e.g., code written before the @ operator for array multiplication).

  2. Matrix Multiplication with *: In matrix objects, * performs matrix multiplication (unlike ndarray, where * is element-wise). Use asmatrix() to enable this behavior.

  3. Library Compatibility: Some older linear algebra libraries or routines may expect matrix inputs. asmatrix() ensures compatibility.

Best Practices#

  1. Prefer ndarray for New Code: The matrix class is legacy. For new projects, use ndarray with @ for matrix multiplication (e.g., arr1 @ arr2).

  2. Use asmatrix() Sparingly: Only use asmatrix() when necessary (e.g., legacy code, library requirements). Overuse can cause type confusion.

  3. Explicit Copy for Independence: If you need an independent matrix (not sharing data with the original array), use asmatrix(data).copy() or numpy.matrix(data).

  4. Clarify * vs @: In matrix, * is matrix multiplication; in ndarray, * is element-wise, and @ is matrix multiplication. Ensure consistency in your code.

Comparison with Similar Functions#

numpy.matrix() vs numpy.asmatrix()#

  • numpy.matrix(data): Always creates a new matrix, copying the data (even if data is already a matrix).
  • numpy.asmatrix(data): Reuses existing matrices (or shares data with ndarray inputs) to avoid unnecessary copying.

Example:

arr = np.array([[1, 2], [3, 4]])
mat_matrix = np.matrix(arr)   # Copies data
mat_asmatrix = np.asmatrix(arr)  # Shares data with arr
 
# Modify the original array
arr[0, 0] = 5
 
print("mat_matrix (copied):\n", mat_matrix)
print("mat_asmatrix (shared):\n", mat_asmatrix)

Output:

mat_matrix (copied):
 [[1 2]
 [3 4]]
mat_asmatrix (shared):
 [[5 2]
 [3 4]]

numpy.asarray() vs numpy.asmatrix()#

  • numpy.asarray(data): Converts data to an ndarray (2D or higher, preserving dimensions).
  • numpy.asmatrix(data): Converts data to a 2D matrix (reshaping 1D inputs to row matrices).

Example:

data = [[1, 2], [3, 4]]
arr = np.asarray(data)   # ndarray
mat = np.asmatrix(data)  # matrix
 
print("arr (ndarray) * arr (ndarray):\n", arr * arr)  # Element-wise
print("mat (matrix) * mat (matrix):\n", mat * mat)    # Matrix multiplication

Output:

arr (ndarray) * arr (ndarray):
 [[ 1  4]
 [ 9 16]]
mat (matrix) * mat (matrix):
 [[ 7 10]
 [15 22]]

Potential Pitfalls#

  1. Inadvertent Data Modification: Modifying a matrix created with asmatrix() (from an ndarray) also modifies the original array (and vice versa). Use copy() to avoid this.

  2. 1D Input Shape Issues: 1D inputs are converted to row matrices (shape (1, n)), which can cause bugs in operations expecting column vectors. Reshape explicitly (e.g., asmatrix(data.reshape(-1, 1))).

  3. Legacy Compatibility: The matrix class is less supported in modern NumPy. Some features may behave differently or be deprecated for matrix inputs.

Conclusion#

numpy.asmatrix() is a useful tool for converting data to a numpy.matrix object, especially in legacy code or for compatibility with older libraries. However, for new projects, prefer ndarray with @ for matrix multiplication to align with modern NumPy practices. Key takeaways:

  • Use asmatrix() sparingly and understand data sharing behavior.
  • Prefer ndarray for new code to avoid type confusion.
  • Explicitly copy data when independence from the original array is needed.

References#