Examples of how to calculate the absolute value of each element of an array or matrix in python with numpy:
Calculate the absolute value for a 1D matrix
Let's first create a 1d matrix with some negative values:
import numpy as np
A = np.linspace(-5.0, 4.0, num=10)
returns
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
To calculate the absolute value of each element of A, a solution is to use numpy.absolute
B = np.absolute(A)
returns then
array([5., 4., 3., 2., 1., 0., 1., 2., 3., 4.])
Note: create some visualization with matplotlib:
Matrix A:
import matplotlib.pyplot as plt
plt.plot(np.arange(A.shape[0]),A)
plt.title("How to calculate the absolute value \n of each element of an array \n or matrix in python with numpy")
plt.grid()
plt.savefig("absolute_01.png", bbox_inches='tight', dpi=100)
plt.show()
gives
Matrix B:
import matplotlib.pyplot as plt
plt.plot(np.arange(B.shape[0]),B)
plt.title("How to calculate the absolute value \n of each element of an array \n or matrix in python with numpy")
plt.savefig("absolute_02.png", bbox_inches='tight', dpi=100)
plt.grid()
plt.show()
gives
Another example with a 2d matrix
Let's create a 2d with some negative values:
A = np.random.randint(-10,10,size=(4,4))
returns for example
array([[-6, -7, -7, 2],
[-7, 1, -6, -8],
[-3, 5, 9, -4],
[ 0, 0, -6, -4]])
Then to calculate the absolute value of each element of A:
B = np.absolute(A)
gives
array([[6, 7, 7, 2],
[7, 1, 6, 8],
[3, 5, 9, 4],
[0, 0, 6, 4]])
Examples of how to visualize the results with matplotlib:
import matplotlib.pyplot as plt
plt.imshow(A)
plt.title("How to calculate the absolute value \n of each element of an array \n or matrix in python with numpy")
plt.grid()
plt.colorbar()
plt.savefig("absolute_03.png", bbox_inches='tight', dpi=100)
plt.show()
gives
import matplotlib.pyplot as plt
plt.imshow(B)
plt.title("How to calculate the absolute value \n of each element of an array \n or matrix in python with numpy")
plt.grid()
plt.colorbar()
plt.savefig("absolute_04.png", bbox_inches='tight', dpi=100)
plt.show()
gives