Issue
I have to find the maximum value of a numpy array ignoring the diagonal elements.
np.amax() provides ways to find it ignoring specific axes. How can I achieve the same ignoring all the diagonal elements?
Solution
You could use a mask
mask = np.ones(a.shape, dtype=bool)
np.fill_diagonal(mask, 0)
max_value = a[mask].max()
where a
is the matrix you want to find the max of. The mask selects the off-diagonal elements, so a[mask]
will be a long vector of all the off-diagonal elements. Then you just take the max.
Or, if you don't mind modifying the original array
np.fill_diagonal(a, -np.inf)
max_value = a.max()
Of course, you can always make a copy and then do the above without modifying the original. Also, this is assuming that a
is some floating point format.
Answered By - hunse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.