user13810183
user13810183

Reputation:

How can I change the shape of an existing array while keeping the contents centered and fill the new spaces with 0's?

I create a numpy matrix using this line of code:

map = np.random.randint(3, size=(7, 7))

How can I change the shape of the matrix to be a 9x9 matrix, while still keeping the contents in the matrix? I'd like the contents to be centered in the 9x9 matrix.

As per comment request, here is an example of an initial matrix, followed by the desired output.

Initial:

[[1 2 1 1 2 2 1]
 [1 0 2 2 0 2 0]
 [2 0 2 1 1 0 2]
 [2 2 2 2 0 1 2]
 [1 1 2 1 0 0 1]
 [2 2 1 1 1 2 1]
 [1 2 0 0 2 2 0]]

Output:

[[0 0 0 0 0 0 0 0 0]
 [0 1 2 1 1 2 2 1 0]
 [0 1 0 2 2 0 2 0 0]
 [0 2 0 2 1 1 0 2 0]
 [0 2 2 2 2 0 1 2 0]
 [0 1 1 2 1 0 0 1 0]
 [0 2 2 1 1 1 2 1 0]
 [0 1 2 0 0 2 2 0 0]
 [0 0 0 0 0 0 0 0 0]]

As you can see, the initial matrix is centered within the new 9x9 matrix.

Upvotes: 1

Views: 46

Answers (1)

Shivam Chauhan
Shivam Chauhan

Reputation: 122

First create your 7x7 matrix:

map7 = np.random.randint(2, size=(7, 7))

Then if you want all zeros around in 9x9 matrix use:

map9 = np.zeros((9,9), dtype=int)

Then place your matrix inside the newly created matrix

map9[1:8,1:8] = map7

Upvotes: 1

Related Questions