Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

finding the minimum value in an array with returned values

I have an array for example:

[1 2 3 4 
 2 3 4 0
 5 4 0 6]

And I want to find the indexes of all the values that are closer to to the value 3.9 (in my example,4)

I tried using :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np
def find_nearest(array, value):
    idx = (np.abs(array - value)).argmin()

and

np.where(array== array.min())

but none of the options gives me the correct answer.

I do excpect to get:

(3,1),(1,2),(2,1)

In my original code, I iterate an array with the shape of 3648X5472 so "FOR" loops might be too heavy.

hope to get some help here, thank you

>Solution :

You can use:

a = np.array([[1, 2, 3, 4], 
              [2, 3, 4, 0],
              [5, 4, 0, 6]])

v = 3.9

b = abs(a-v)

xs, ys = np.where(b == np.min(b))

output:

>>> xs
array([0, 1, 2])

>>> ys
array([3, 2, 1])

Alternative output:

>>> np.c_[np.where(b == np.min(b))]
array([[0, 3],
       [1, 2],
       [2, 1]])
# or 
>>> np.argwhere(b==np.min(b))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading