Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum of Numpy Array Ignoring Diagonal

Tags:

python

numpy

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?

like image 321
Erdnase Avatar asked Apr 01 '15 15:04

Erdnase


People also ask

How do you find the diagonal of a NumPy array?

Numpy diag() function is used to extract or construct a diagonal 2-d array. It contains two parameters: an input array and k , which decides the diagonal, i.e., k=0 for the main diagonal, k=1 for the above main diagonal, or k=-1 for the below diagonal.

Does NumPy array have fixed size?

NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original. The elements in a NumPy array are all required to be of the same data type, and thus will be the same size in memory.


1 Answers

This should work:

import numpy as np
import numpy.random

# create sample matrix
a = numpy.random.randint(10,size=(8,8))
a[0,0] = 100

which looks like

array([[100, 8, 6, 5, 5, 7, 4, 5],
   [4, 6, 1, 7, 4, 5, 8, 5],
   [0, 2, 0, 7, 4, 2, 7, 9],
   [5, 7, 5, 9, 8, 3, 2, 8],
   [2, 1, 3, 4, 0, 7, 8, 1],
   [6, 6, 7, 6, 0, 6, 6, 8],
   [6, 0, 1, 9, 7, 7, 9, 3],
   [0, 5, 5, 5, 1, 5, 4, 4]])
# create mask
mask = np.ones((8,8)) 
mask = (mask - np.diag(np.ones(8))).astype(np.bool)

which looks like:

array([[False,  True,  True,  True,  True,  True,  True,  True],
   [ True, False,  True,  True,  True,  True,  True,  True],
   [ True,  True, False,  True,  True,  True,  True,  True],
   [ True,  True,  True, False,  True,  True,  True,  True],
   [ True,  True,  True,  True, False,  True,  True,  True],
   [ True,  True,  True,  True,  True, False,  True,  True],
   [ True,  True,  True,  True,  True,  True, False,  True],
   [ True,  True,  True,  True,  True,  True,  True, False]], dtype=bool)

Then

# calculate the maximum
out = np.amax(a[mask])

Output:

9
like image 148
plonser Avatar answered Sep 18 '22 17:09

plonser