# How To extract all possible sub arrays of a 2D array

Share

## what is the number of sub matrices of MxN matrix

The number of submatrices in an MxN matrix can be calculated using the formula:

(1 + 2 + ... + M) * (1 + 2 + ... + N)=(M * (M + 1) / 2) * (N * (N + 1) / 2)


This formula works for matrices of any size, including square matrices (M = N).

def count_submatrices(m, n):
return (m * (m + 1) // 2) * (n * (n + 1) // 2)

m = 3
n = 4
num_submatrices = count_submatrices(m, n)
print(num_submatrices)


## extract submatrix/subarray from numpy matrix/array

To extract all possible sub-arrays of a 2D NumPy array, you can use a nested loop to iterate over all possible combinations of starting and ending indices for the rows and columns.

import numpy as np

# Create a 2D NumPy array
a = np.array(range(9)).reshape((3, 3))

# Extract all possible sub-arrays of a
sub_arrays = []
for i in range(a.shape):
for j in range(a.shape):
for k in range(i+1, a.shape+1):
for l in range(j+1, a.shape+1):
sub_arrays.append(a[i:k, j:l])

# Print the sub-arrays
for sub_array in sub_arrays:
print(sub_array)


In this code, we first create the 2D NumPy array a.

We then define a list sub_arrays to hold all the sub-arrays of a.

Next, we use four nested loops to iterate over all possible combinations of starting and ending indices for the rows and columns of a. Specifically, the outer two loops iterate over the starting row and column indices, while the inner two loops iterate over the ending row and column indices. We add each sub-array to the list sub_arrays.

Finally, we print all the sub-arrays in sub_arrays using a for loop.

output:

[]

[[0 1]]

[[0 1 2]]

[
]

[[0 1]
[3 4]]

[[0 1 2]
[3 4 5]]

[

]

[[0 1]
[3 4]
[6 7]]

[[0 1 2]
[3 4 5]
[6 7 8]]

[]

[[1 2]]

[
]

[[1 2]
[4 5]]

[

]

[[1 2]
[4 5]
[7 8]]

[]

[
]

[

]

[]

[[3 4]]

[[3 4 5]]

[
]

[[3 4]
[6 7]]

[[3 4 5]
[6 7 8]]

[]

[[4 5]]

[
]

[[4 5]
[7 8]]

[]

[
]

[]

[[6 7]]

[[6 7 8]]

[]

[[7 8]]

[]

Share
Top 5 Most Expensive Domains Ever Sold 4 Must-Try ChatGPT Alternatives: Perplexity AI, BardAI, Pi, and More! Types of Trading Techniques in the Stock Market. ChatGPT app now available in India this AI chatbot can help you make your life more productive. What is wrong with following function code?