Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy getting the not min or max element out of three elements

Tags:

python

numpy

I have a three dimensional array :

 y = np.random.randint(1,5 ,(50,50,3))

I want to compute the max and min across the third axis (3 elements), and then divide by the remaining number/element.

So something like this:

x = (np.max(y, axis =2) - 2*np.min(y, axis =2))/the third number

I don't know how to get the third number. Something to beware of is, the third number has the possibility of being equal to the min or max value:

e.g. (5,5,1)

like image 600
Moondra Avatar asked Dec 07 '22 16:12

Moondra


2 Answers

While usually sorting is overkill when you only need a max and min, in this case I think it's the simplest. It directly puts the numbers we want in places it's easy to access, without any complex arithmetic.

y = np.random.randint(1, 5, (50, 50,3))
y2 = y.copy()
y2.sort(axis=2)
sout = (y2[...,2] - 2 * y2[...,0]) / y2[...,1]

which gives me

In [68]: (sout == divakar_out).all()
Out[68]: True

which is usually a good sign. ;-)

like image 178
DSM Avatar answered Jan 17 '23 07:01

DSM


Another alternative is to use np.median

(y.max(2) - 2 * y.min(2)) / np.median(y, 2)
like image 31
piRSquared Avatar answered Jan 17 '23 07:01

piRSquared