M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
matrix_length = len(M1)
#To read the last element from each row.
for i in range(matrix_length):
print(M1[i][-1])
示例 3:打印矩阵中的行
M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
matrix_length = len(M1)
#To print the rows in the Matrix
for i in range(matrix_length):
print(M1[i])
[8, 14, -6]
[12, 7, 4]
[-11, 3, 21]
M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
M2 = [[3, 16, -6],
[9,7,-4],
[-1,3,13]]
M3 = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(M1)
#To Add M1 and M2 matrices
for i in range(len(M1)):
for k in range(len(M2)):
M3[i][k] = M1[i][k] + M2[i][k]
#To Print the matrix
print("The sum of Matrix M1 and M2 = ", M3)
The sum of Matrix M1 and M2 = [[11, 30, -12], [21, 14, 0], [-12, 6, 34]]
使用嵌套列表进行矩阵乘法
为了将矩阵相乘,我们可以在两个矩阵上使用 for 循环,如下面的代码所示:
M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
M2 = [[3, 16, -6],
[9,7,-4],
[-1,3,13]]
M3 = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(M1)
#To Multiply M1 and M2 matrices
for i in range(len(M1)):
for k in range(len(M2)):
M3[i][k] = M1[i][k] * M2[i][k]
#To Print the matrix
print("The multiplication of Matrix M1 and M2 = ", M3)
The multiplication of Matrix M1 and M2 = [[24, 224, 36], [108, 49, -16], [11, 9, 273]]
import numpy as np
arr = np.array([2,4,6,8,10,12,14,16])
print(arr[3:6]) # will print the elements from 3 to 5
print(arr[:5]) # will print the elements from 0 to 4
print(arr[2:]) # will print the elements from 2 to length of the array.
print(arr[-5:-1]) # will print from the end i.e. -5 to -2
print(arr[:-1]) # will print from end i.e. 0 to -2
[ 8 10 12]
[ 2 4 6 8 10]
[ 6 8 10 12 14 16]
[ 8 10 12 14]
[ 2 4 6 8 10 12 14]
现在让我们在矩阵上实现切片。对矩阵进行切片
import numpy as np
M1 = np.array([[2, 4, 6, 8, 10],
[3, 6, 9, -12, -15],
[4, 8, 12, 16, -20],
[5, -10, 15, -20, 25]])
print(M1[1:3, 1:4]) # For 1:3, it will give first and second row.
#The columns will be taken from first to third.
[[ 6 9 -12]
[ 8 12 16]]
示例:打印所有行和第三列
import numpy as np
M1 = np.array([[2, 4, 6, 8, 10],
[3, 6, 9, -12, -15],
[4, 8, 12, 16, -20],
[5, -10, 15, -20, 25]])
print(M1[:,3]) # This will print all rows and the third column data.
[ 8 -12 16 -20]
示例:打印第一行和所有列
import numpy as np
M1 = np.array([[2, 4, 6, 8, 10],
[3, 6, 9, -12, -15],
[4, 8, 12, 16, -20],
[5, -10, 15, -20, 25]])
print(M1[:1,]) # This will print first row and all columns
[[ 2 4 6 8 10]]