En este artículo, discutiremos cómo sumar y restar elementos de la array en Python.
Ejemplo:
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]]
Ahora intentemos implementar esto usando Python
1. Sumar elementos de la array
En el código anterior, hemos usado el método np.add() para agregar elementos de dos arrays. arr1.forma != arr2.forma
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))
Producción:
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. Restar elementos de arrays
En el código anterior, hemos usado np.subtract() para restar elementos de dos arrays
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))
Producción:
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]]
Publicación traducida automáticamente
Artículo escrito por Akashkumar17 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA