Numpy
Numpy
a = np.array([1, 2, 3, 4])
print(a)
[1 2 3 4]
[[1 2 3]
[4 5 6]]
[[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]
[1. 1.]]
e = np.full((2, 2), 7)
print(e)
[[7 7]
[7 7]]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
h = np.array([1, 2, 3])
i = np.array([4, 5, 6])
array_addition = h + i
print(array_addition)
[5 7 9]
[ 4 10 18]
[[19 22]
[43 50]]
## 4. Array Statistics
#Mean of an array:
mean_val = np.mean(f)
print(mean_val)
9.5
std_dev = np.std(f)
print(std_dev)
5.766281297335398
total_sum = np.sum(f)
print(total_sum)
190
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
#Flatten a 2D array:
flattened = reshaped.flatten()
print(flattened)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[[2 3]
[5 6]]
squared_array = np.sqrt(f)
print(squared_array)
print(b)
print()
[[1 2 3]
[4 5 6]]
[5 7 9]
[ 6 15]
[[2 6 0]
[6 2 0]]
[[0.15120192 0.46644157]
[0.40234905 0.27096769]]
# Matrix multiplication
C = np.dot(A, B)
# Alternatively: C = A @ B
print(C)
[[19 22]
[43 50]]
# Solve for x
x = np.linalg.solve(A, b)
print(x)
[-0.5 3.25]
#3. Matrix Decomposition
#Matrix decompositions such as LU decomposition, QR decomposition, and Singular Value Decomposition (SVD) are crucial in numerical analy
#LU Decomposition
from scipy.linalg import lu
# LU decomposition
P, L, U = lu(A)
print("P:", P)
print("L:", L)
print("U:", U)
P: [[1. 0.]
[0. 1.]]
L: [[1. 0. ]
[0.33333333 1. ]]
U: [[3. 2. ]
[0. 1.33333333]]
# Compute determinant
det = np.linalg.det(A)
print("Determinant:", det)
Determinant: -2.0000000000000004
# 6. Matrix Inversion
# Inverting a matrix is necessary for solving linear systems and other applications.
Inverse of A:
[[-2. 1. ]
[ 1.5 -0.5]]
#7. Norms
#Matrix norms and vector norms help in assessing the magnitude of vectors and matrices.
v = np.array([1, 2, 3])
Norm of v: 3.7416573867739413
##8. Rank of a Matrix
## Determining the rank of a matrix helps in understanding its properties.
Rank of A: 1