I have a 2D matrix and I want to take norm of each row. But when I use numpy.linalg.norm(X)
directly, it takes the norm of the whole matrix.
I can take
Try the following:
In [16]: numpy.apply_along_axis(numpy.linalg.norm, 1, a)
Out[16]: array([ 5.38516481, 1.41421356, 5.38516481])
where a
is your 2D array.
The above computes the L2 norm. For a different norm, you could use something like:
In [22]: numpy.apply_along_axis(lambda row:numpy.linalg.norm(row,ord=1), 1, a)
Out[22]: array([9, 2, 9])