w3resource

NumPy: Create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0


10x10 Matrix Border 1, Inside 0

Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.

This problem involves writing a NumPy program to generate a 10x10 matrix where the border elements are set to 1 and the inner elements are set to 0. The task requires utilizing NumPy's array manipulation capabilities to efficiently create the matrix with the specified values. By setting the border elements to 1 and the inner elements to 0, the resulting matrix represents a common pattern used in various computational and mathematical contexts.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 10x10 matrix filled with ones using np.ones()
x = np.ones((10, 10))

# Setting the inner values of the matrix 'x' (excluding the borders) to 0 using slicing
x[1:-1, 1:-1] = 0

# Printing the modified matrix 'x'
print(x) 

Output:

[[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]                         

Explanation:

In the above code -

np.ones((10, 10)) creates a 10x10 array 'x' filled with ones.

‘x[1:-1, 1:-1] = 0’ uses array slicing to select the inner region of the array 'x' and set its elements to zeros. The slice 1:-1 means "from the second element to the second-to-last element" in both the rows and columns. As a result, the inner region of the array will be filled with zeros, leaving a border of ones.

Finally print(x) prints the modified array to the console.

Visual Presentation:

NumPy: Create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.

Python-Numpy Code Editor: