Write a NumPy program to extract all the contiguous 4x4 blocks from a given random 12x12 matrix.
import numpy as np arra1 = np.random.randint(0,5,(12,12)) print("Original arrays:") print(arra1) n = 4 i = 1 + (arra1.shape[0]-4) j = 1 + (arra1.shape[1]-4) result = np.lib.stride_tricks.as_strided(arra1, shape=(i, j, n, n), strides = arra1.strides + arra1.strides) print("\nContiguous 4x4 blocks:") print(result)
Sample Output:
Original arrays: [[3 3 1 2 0 3 0 3 2 0 1 0] [4 0 4 2 0 0 0 0 2 2 2 3] [1 4 0 1 1 3 4 1 0 3 3 3] [1 4 2 4 2 0 0 4 2 1 2 3] [4 3 0 2 3 1 0 1 1 1 2 2] [1 0 1 1 4 4 3 1 4 2 3 4] [1 4 0 4 1 2 0 2 4 1 4 4] [2 2 0 4 1 4 2 4 1 4 0 3] [3 0 4 0 3 1 2 4 4 1 1 0] [3 1 3 3 0 0 4 3 1 0 2 2] [1 2 3 4 1 2 3 4 3 2 3 4] [4 0 4 2 2 4 1 4 2 0 0 0]] Contiguous 4x4 blocks: [[[[3 3 1 2] [4 0 4 2] [1 4 0 1] [1 4 2 4]] [[3 1 2 0] [0 4 2 0] [4 0 1 1] [4 2 4 2]] [[1 2 0 3] [4 2 0 0] [0 1 1 3] [2 4 2 0]] ... [[0 3 2 0] [0 0 2 2] [4 1 0 3] [0 4 2 1]] [[3 2 0 1] [0 2 2 2] [1 0 3 3] [4 2 1 2]] [[2 0 1 0] [2 2 2 3] [0 3 3 3] [2 1 2 3]]] [[[4 0 4 2] [1 4 0 1] [1 4 2 4] [4 3 0 2]] [[0 4 2 0] [4 0 1 1] [4 2 4 2] [3 0 2 3]] [[4 2 0 0] [0 1 1 3] [2 4 2 0] [0 2 3 1]] ... [[0 0 2 2] [4 1 0 3] [0 4 2 1] [0 1 1 1]] [[0 2 2 2] [1 0 3 3] [4 2 1 2] [1 1 1 2]] [[2 2 2 3] [0 3 3 3] [2 1 2 3] [1 1 2 2]]] [[[1 4 0 1] [1 4 2 4] [4 3 0 2] [1 0 1 1]] [[4 0 1 1] [4 2 4 2] [3 0 2 3] [0 1 1 4]] [[0 1 1 3] [2 4 2 0] [0 2 3 1] [1 1 4 4]] ... [[4 1 0 3] [0 4 2 1] [0 1 1 1] [3 1 4 2]] [[1 0 3 3] [4 2 1 2] [1 1 1 2] [1 4 2 3]] [[0 3 3 3] [2 1 2 3] [1 1 2 2] [4 2 3 4]]] ... [[[1 4 0 4] [2 2 0 4] [3 0 4 0] [3 1 3 3]] [[4 0 4 1] [2 0 4 1] [0 4 0 3] [1 3 3 0]] [[0 4 1 2] [0 4 1 4] [4 0 3 1] [3 3 0 0]] ... [[0 2 4 1] [2 4 1 4] [2 4 4 1] [4 3 1 0]] [[2 4 1 4] [4 1 4 0] [4 4 1 1] [3 1 0 2]] [[4 1 4 4] [1 4 0 3] [4 1 1 0] [1 0 2 2]]] [[[2 2 0 4] [3 0 4 0] [3 1 3 3] [1 2 3 4]] [[2 0 4 1] [0 4 0 3] [1 3 3 0] [2 3 4 1]] [[0 4 1 4] [4 0 3 1] [3 3 0 0] [3 4 1 2]] ... [[2 4 1 4] [2 4 4 1] [4 3 1 0] [3 4 3 2]] [[4 1 4 0] [4 4 1 1] [3 1 0 2] [4 3 2 3]] [[1 4 0 3] [4 1 1 0] [1 0 2 2] [3 2 3 4]]] [[[3 0 4 0] [3 1 3 3] [1 2 3 4] [4 0 4 2]] [[0 4 0 3] [1 3 3 0] [2 3 4 1] [0 4 2 2]] [[4 0 3 1] [3 3 0 0] [3 4 1 2] [4 2 2 4]] ... [[2 4 4 1] [4 3 1 0] [3 4 3 2] [1 4 2 0]] [[4 4 1 1] [3 1 0 2] [4 3 2 3] [4 2 0 0]] [[4 1 1 0] [1 0 2 2] [3 2 3 4] [2 0 0 0]]]]
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer