Python中的矩阵加减法
在这篇文章中,我们将讨论如何在Python中对矩阵元素进行加减。
示例:
Suppose we have two matrices A and B.
A = [[1,2],[3,4]]
B = [[4,5],[6,7]]
then we get
A+B = [[5,7],[9,11]]
A-B = [[-3,-3],[-3,-3]]
现在让我们试着用Python来实现这一点
1.添加矩阵的元素
在上面的代码中,我们使用了np.add()方法来添加两个矩阵的元素。 如果两个数组的形状不一样,即arr1.shape != arr2.shape ,它们必须可广播到一个共同的形状(可能是一个或另一个的形状)。
# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B))
输出:
Printing elements of first matrix
[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Addition of two matrix
[[ 5 7]
[ 9 11]]
2.减去矩阵的元素
在上面的代码中,我们使用了np.subtract()来减去两个矩阵的元素。它返回 arr1 和 arr2 的差值,按元素计算。
# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# subtracting two matrix
print("Subtraction of two matrix")
print(np.subtract(A, B))
输出:
Printing elements of first matrix
[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Subtraction of two matrix
[[-3 -3]
[-3 -3]]