在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 ,它们必须可以广播到一个共同的形状(可能是一个或另一个的形状)。
Python3
# 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))
Python3
# 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]]
Addition of two matrix
[[ 5 7]
[ 9 11]]
2.减去矩阵的元素
在上面的代码中,我们使用 np.subtract() 来减去两个矩阵的元素。它按元素返回 arr1 和 arr2 的差异。
Python3
# 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]]