Numpy Programs
Numpy Programs
This problem involves writing a NumPy program to generate a 3x4 matrix filled
with consecutive values starting from 10 and ending at 21. The task requires
utilizing NumPy's array creation functionalities to efficiently construct the matrix
with the specified range of values while maintaining the desired dimensions.
import numpy as np
m = np.arange(10, 22).reshape((3, 4))
print(m)
o/p
[[10 11 12 13]
[14 15 16 17]
[18 19 20 21]]
o/p
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
An identity matrix is a square matrix with ones on its main diagonal and zeros
elsewhere.
In the above code the line ‘x = np.eye(3)’ uses the np.eye() function to create a
2-dimensional square identity matrix 'x' of size 3x3.
Visual Presentation:
Write a NumPy program to create a 5x5 zero matrix with
elements on the main diagonal equal to 1, 2, 3, 4, 5?
This problem involves writing a NumPy program to generate a 5x5 matrix where
all elements are initially set to zero, except for the main diagonal, which is filled
with the values 1, 2, 3, 4, and 5. The task requires utilizing NumPy's array
manipulation capabilities to efficiently construct and modify the matrix, ensuring
the specified values are placed correctly on the diagonal. The resulting matrix
combines elements of identity matrices with custom diagonal values.
import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)
o/p
[[1 0 0 0 0]
[0 2 0 0 0]
[0 0 3 0 0]
[0 0 0 4 0]
[0 0 0 0 5]]
Explanation:
The above exercise creates a 5x5 square matrix with the main diagonal elements
[1, 2, 3, 4, 5] and zeros elsewhere, and prints the resulting matrix.
In the above code np.diag([1, 2, 3, 4, 5]) creates a 2D square matrix with the
specified diagonal elements [1, 2, 3, 4, 5]. The rest of the elements in the matrix
are filled with zeros.
Finally print(x) prints the generated matrix to the console.
Visual Presentation:
print("Original array:")
print(x)
o/p
Original array:
[[0 1]
[2 3]]
Sum of all elements:
6
Sum of each column:
[2 4]
Sum of each row:
[1 5]
Explanation:
‘x = np.array([[0, 1], [2, 3]])’ creates a 2D array 'x' with the shape (2, 2) and
elements [[0, 1], [2, 3]].
Visual Presentation: