w3resource

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

NumPy: Basic Exercise-28 with Solution

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

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) 

Sample 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.

Pictorial 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:

Previous: NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1,the rest are 0.
Next: NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.