Following is a tutorial on how to square a matrix in Numpy Python library.
Using a numpy square method
The easiest way and the most convenient one is just to use a built-in function of Numpy square. It just take my array as an argument and squares it.
import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = np.square(my_array) print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")
As an output you can see that my array got squared as expected.
Using a numpy power method
You can also use power Numpy method. Square is the same as second power so it will work the same.
import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = np.power(my_array, 2) print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")
Using asterisks
The most pythonic way would be to use ** 2 which also square my array.
import numpy as np my_array = np.array([1, 2, 3, 4]) squared_array = my_array ** 2 print(f"My array is equal to {my_array}") print(f"Squared array is equal to {squared_array}")
These are 3 different ways to square a matrix using Numpy. Of course Numpy square function is the most efficient one for a comercial purpose.