Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the highest element in absolute value in a numpy matrix?

Tags:

python

numpy

Here is what I am currently doing, it works but it's a little cumbersome:

x = np.matrix([[1, 1], [2, -3]]) xmax = x.flat[abs(x).argmax()] 
like image 737
qed Avatar asked Jul 22 '13 18:07

qed


People also ask

How do you find the element-wise absolute value of a NumPy array?

To calculate the absolute value, we can use two methods, fabs() and absolute(). To return the absolute value element-wise, use the numpy. fabs() method in Python Numpy.

How do you find the absolute value of a matrix in python?

Python has two ways to get the absolute value of a number: The built-in abs() function returns the absolute value. The math. fabs() function also returns the absolute value, but as a floating-point value.


1 Answers

The value you're looking for has to be either x.max() or x.min() so you could do

max(x.min(), x.max(), key=abs) 

which is similar to aestrivex's solution but perhaps more readable? Note this will return the minimum in the case where x.min() and x.max() have the same absolute value e.g. -5 and 5. If you have a preference just order the inputs to max accordingly.

like image 146
JoeCondron Avatar answered Sep 17 '22 23:09

JoeCondron