Assignment0 M
Assignment0 M
Muskan
11/02/24
1 Question 1 :
Find out the size of array ’a’, ’b’, and ’c’. In the following code block.
import numpy as np
a = np . array (42)
b = np . array ([1 , 2, 3 , 4 , 5])
c = np . array ([[1 , 2, 3] , [4 , 5, 6]])
# Print size of all arrays
CODE:
import numpy as np
a = np.array ([42])
b = np.array ([1 , 2, 3 , 4 , 5])
c = np.array ([[1 , 2, 3] , [4 , 5, 6]])
size=[]
x=c
for m in [a,b,c]:
count=0
for i in m:
try:
for j in i:
count+=1
except:
count+=1
print(f’Size of the array {m} is {count}’)
2 Question 2 :
Bins! Yes binning might be tricky if you want to plot meaningful plots, in
the below histogram choose an appropriate binning size, expiriment with the
bins style, location, borders and colors. Explore the np.arange function. Add
meaningful labels to both axes.
1
import matplotlib . pyplot as plt
val = np . random . normal ( size =(100) , scale =3 , loc =10)
# bins =np. arange (0 ,20 ,1)
plt . hist ( val , bins =20)
plt . show ()
CODE:
import numpy as np
import matplotlib.pyplot as plt
val = np.random.normal(size =(100) , scale =3 , loc =8)
bins =np. arange (0 ,20 ,1)
plt.hist ( val , bins =20, color= ’r’, edgecolor= ’blue’)
plt.xlabel(’X-axis’)
plt.ylabel(’Y-axis’)
plt.show ()
3 Question 3 :
Array adressing and slicing. As the dimensions of the array increase it becomes
very important how one indexes those arrays, slicing becomes important when
one wants to get some desired subpart of a whole array. This Question has two
parts. 3.1. Print the sum of left diagonal and right diagonal of a square matrix.
mat = np . array ([[1 ,3 ,4 ,5 ,2] ,[1 ,5 ,2 ,4 ,3] ,[5 ,2 ,3 ,4 ,1 ,]
,[1 ,4 ,2 ,6 ,9] ,[4 ,5 ,2 ,1 ,7]])
def left_diagonal_sum ( mat : np . ndarray ) ->float :
# write your logic here
pass
def right_diagonal_sum ( mat : np . ndarray ) ->float :
# write your logic here
pass
print (f’Left Diagonal Sum of { mat =} is { left_diagonal_sum (mat)}’)
print (f’Right Diagonal Sum of { mat =} is { right_diagonal_sum ( mat )}’)
3.2. From the matrix of previous part, print the 3x4 sub-matrix from 1st row
2nd column to 3rd row 5th column. Make use of the array slicing operations
preferably , use of for loops is discouraged.
def submatrix_3x4 ( mat : np . ndarray ) -> np . ndarray :
# write your logic here
pass
print (f’The desired submatrix of \n { mat } is \n { submatrix_3x4 ( mat )}’)’)
CODE:
2
import numpy as np
mat = np.array ([[1 ,3 ,4 ,5 ,2] ,[1 ,5 ,2 ,4 ,3] ,[5 ,2 ,3 ,4 ,1 ] ,
[1 ,4 ,2 ,6 ,9] ,[4 ,5 ,2 ,1 ,7]])
def left_diagonal_sum (mat):
sum=0
for i in range(len(mat)):
for j in range(len(mat[i])):
if i==j:
sum=mat[i][j]+sum
return sum
pass
def right_diagonal_sum (mat):
sum=0
for i in range(len(mat)):
for j in range(len(mat[i])):
if i+j==(len(mat)-1):
sum=sum+mat[i][j]
return sum
pass
print(f’Left Diagonal Sum of \n { mat =} is { left_diagonal_sum(mat)}’)
print(f’Right Diagonal Sum of \n { mat =} is { right_diagonal_sum(mat)}’)
def submatrix_3x4(mat):
sub_mat=mat[0:3, 1:5]
return sub_mat
pass
print (f’The desired submatrix of \n { mat } is \n {submatrix_3x4(mat)}’)
4 Question 4 :
array operations in np.array and np.math functions. Plot the function:
sin7 (x) + cos5 (x)
f (x) =
ex
in the domain :
x ∈ [0, 4]
Do not use for loops for the same.
def f(x: np . ndarray ) -> np . ndarray :
# write your logic here
pass
steps =1000 # experiment how step size matters in the graph shape
x= np.arange (0 ,4,steps)
y= f(x)
plt . plot (x ,y) # label the axes , and choose appropriate plot format and style
plt . show ()
3
CODE:
import numpy as np
import matplotlib.pyplot as plt
def f(x: np.ndarray) -> np.ndarray:
return ((np.sin(x))**7+(np.cos(x))**5)/np.exp(x)
steps =0.1 # experiment how step size matters in the graph shape
x= np.arange(0 ,4 , steps )
y= f(x)
plt.plot(x,y, color="hotpink") # label the axes , and choose appropriate plot format and sty
plt.show()
5 Question 5 :
Create a subplot with two plots side by side. Plot a sine wave in the first sub-
plot. Plot a cosine wave in the second subplot. Add labels, titles, and a legend
to the plots.
CODE:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10, 5))
#sin
plt.subplot(1, 2, 1)
plt.plot(x, y1, label=’Sine Wave’, color=’hotpink’)
plt.xlabel(’X’)
plt.ylabel(’Amplitude’)
plt.title(’Sine Wave Plot’)
plt.legend()
#cos
plt.subplot(1, 2, 2)
plt.plot(x, y2, label=’Cosine Wave’, color=’hotpink’)
plt.xlabel(’X’)
plt.ylabel(’Amplitude’)
plt.title(’Cosine Wave Plot’)
plt.legend()
plt.tight_layout()
plt.show()
4
5