w3resource

NumPy: Create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal

NumPy: Basic Exercise-30 with Solution

Write a NumPy program to create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.

Sample Solution :

Python Code :

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

# Creating a 4x4 matrix filled with zeros using np.zeros()
x = np.zeros((4, 4))

# Setting elements in alternate rows and columns to 1
# Setting elements in even rows (0-based indexing) and odd columns to 1
x[::2, 1::2] = 1

# Setting elements in odd rows and even columns to 1
x[1::2, ::2] = 1

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

Sample Output:

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

Explanation:

In the above code -

In ‘x = np.zeros((4, 4))’ statement the np.zeros() function is used to create a 4x4 array 'x' filled with zeros.

x[::2, 1::2] = 1: This line uses array slicing to select every other row (starting from the first row) and every other column (starting from the second column) in the array 'x' and sets their elements to ones. The slice ::2 means "every second element" in both the rows and columns, while the slice 1::2 means "every second element, starting from the second element".

x[1::2, ::2] = 1: This line uses array slicing to select every other row (starting from the second row) and every other column (starting from the first column) in the array 'x' and sets their elements to ones. The slice 1::2 means "every second element, starting from the second element" in both the rows and columns.

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

Pictorial Presentation:

NumPy: Create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.

Python-Numpy Code Editor:

Previous: NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.
Next: NumPy program to create a 3x3x3 array filled with arbitrary values.

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.