Numpy: How to extract a Submatrix from an array

Borislav Hadzhiev

Last updated: Apr 12, 2024

Reading time·4 min

**Use the numpy.ix_() method to extract a submatrix from an array.**

**The method returns N arrays with N dimensions each, where N is the number of
input sequences.**

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[np.ix_([0, 3], [1, 3])] # [[ 2 4] # [14 16]] print(submatrix)`

The code for this article is available on GitHub

Running the code sample produces the following output.

shell

`[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] -------------------------------------------------- [[ 2 4] [14 16]]`

The numpy.ix_ method constructs an open mesh from multiple sequences.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) # (array([[0], [3]]), array([[1, 3]])) print(np.ix_([0, 3], [1, 3]))`

The `ix_()`

method returns a tuple of `ndarrays`

.

Each array has N dimensions with N being the number of input sequences.

Together the arrays form an open mesh.

The arrays are then used to index the original array.

The following example extracts the first and fourth elements of the first row and the first and fourth elements of the last row.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[np.ix_([0, 3], [0, 3])] # [[ 1 4] # [13 16]] print(submatrix)`

The code for this article is available on GitHub

The following example extracts the second and fourth elements of the second row and the second and fourth elements of the fourth row.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[np.ix_([1, 3], [1, 3])] # [[ 6 8] # [14 16]] print(submatrix)`

The following example extracts the first and third elements of the first row and the first and third elements of the third row.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[np.ix_([0, 2], [0, 2])] # [[ 1 3] # [ 9 11]] print(submatrix)`

You can also use array indexing to extract a submatrix from a NumPy array.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[0:4:3, 0:4:3] # [[ 1 4] # [13 16]] print(submatrix)`

The code for this article is available on GitHub

The example selects every third column from the first to the last.

Note that array indices are zero-based, so the first element in an array has an
index of `0`

and the last has an index of `len(array) - 1`

.

The following example selects every second column from the first to the last.

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], ]) print(arr) print('-' * 50) submatrix = arr[0:5:2, 0:5:2] # [[ 1 3] # [ 9 11] # [17 19]] print(submatrix)`

The following example selects rows 0, 1, 2 (0-2) and columns 1, 2, 3 (1-3).

main.py

`import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], ]) print(arr) print('-' * 50) submatrix = arr[0:3, 1:4] # [[ 2 3 4] # [ 6 7 8] # [10 11 12]] print(submatrix)`

The code for this article is available on GitHub

Notice that indexing is zero-based.

`0:3`

means "select rows 0, 1 and 2".`1:4`

means "select columns 1, 2 and 3".

You can learn more about the related topics by checking out the following tutorials:

- TypeError: 'numpy.ndarray' object is not callable in Python
- TypeError: Object of type ndarray is not JSON serializable
- IndexError: too many indices for array in Python [Solved]
- How to filter a JSON array in Python
- AttributeError module 'numpy' has no attribute array or int
- How to check if a NumPy Array is multidimensional or 1D
- NumPy: Calculate the distance between a Point and a Line
- Pandas: Changing the column type to Categorical
- Pandas: Get a List of Categories or Categorical Columns
- Reduction operation 'argmax' not allowed for this dtype
- numpy.linalg.LinAlgError: Singular matrix [Solved]
- Removing the Top and Right axis (spines) in Matplotlib
- NumPy: Unable to allocate array with shape and data type
- NumPy RuntimeWarning: invalid value encountered in divide
- All the input arrays must have same number of dimensions
- Only integer scalar arrays can be converted to a scalar index
- ValueError: Index contains duplicate entries, cannot reshape
- TypeError: type numpy.ndarray doesn't define __round__ method
- OSError: [E050] Can't find model 'en_core_web_sm'
- ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1002)