Understanding `matrix.ndim` in NumPy (Even Though You Should Use `ndarray`)


  • matrix.ndim attribute
    This attribute specifically applies to the matrix subclass and returns the number of dimensions of the matrix. Just like with ndarray, the number of dimensions determines the shape of the data. For instance, a 2D matrix has two dimensions (rows and columns), and a 3D matrix has three dimensions (typically depth, rows, and columns).

  • Standard array subclasses in NumPy
    The ndarray class in NumPy represents a general n-dimensional array. Several standard array subclasses inherit properties and functionality from ndarray, including matrix. These subclasses can provide domain-specific behaviors or views on the underlying data.

Key points to remember

  • The ndim attribute works similarly for both ndarray and matrix (when used).
  • While matrix.ndim is still functional for existing code using matrix, it's recommended to use ndarray directly for new projects as it offers more flexibility and is the preferred way to work with multidimensional data in NumPy.


Example 1: Checking dimensions of a 2D matrix

import numpy as np

# Create a 2D matrix using the matrix class (deprecated)
matrix = np.matrix([[1, 2, 3], [4, 5, 6]])

# Check the number of dimensions using ndim
num_dimensions = matrix.ndim

print("Number of dimensions:", num_dimensions)  # Output: Number of dimensions: 2

Example 2: Checking dimensions of a 1D array

import numpy as np

# Create a 1D array using matrix (deprecated)
array = np.matrix([1, 2, 3])

# Check the number of dimensions
num_dimensions = array.ndim

print("Number of dimensions:", num_dimensions)  # Output: Number of dimensions: 1
import numpy as np

# Create a 2D array using ndarray
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Check number of dimensions
num_dimensions = array_2d.ndim

print("Number of dimensions (using ndarray):", num_dimensions)  # Output: Number of dimensions (using ndarray): 2


Original approach (deprecated)

import numpy as np

matrix = np.matrix([[1, 2, 3], [4, 5, 6]])
num_dimensions = matrix.ndim

Recommended approach

import numpy as np

array = np.array([[1, 2, 3], [4, 5, 6]])
num_dimensions = array.ndim

Both approaches achieve the same result: obtaining the number of dimensions of the multidimensional data structure.

Here are some additional ways to check the dimensionality of an array in NumPy, although they don't directly use ndim:

  1. Using shape attribute
    The shape attribute of an ndarray returns a tuple representing the size of each dimension. The length of this tuple indicates the number of dimensions.
array_shape = array.shape
num_dimensions = len(array_shape)
  1. Using built-in functions
    Libraries like scipy offer functions to check array properties. For example, scipy.ndimage.ndim can also be used, although it's less common for NumPy arrays specifically.
from scipy import ndimage

num_dimensions = ndimage.ndim(array)