1

Suppose I have a variable arr that stores multiple 3D arrays.

arr = [[[1,2,3],
       [4,5,6],
       [10,11,12]]]

      [[[13,14,15],
        [16,17,18],
        [19,20,21]]]

How can I get the nearest values to the corresponding given values in variable vals from the arr. The nearest value for the first value in vals should be searched only in 1st array of the arr and similarly second one in the second array

vals = np.array([3.2, 6.8])

The expected outcome:

nearest values = [3, 13]
mArk
  • 630
  • 8
  • 13
  • Flatten and use linked Q&A : `arr.flat[closest_argmin(vals, arr.ravel())]` for `arr` as array. – Divakar May 09 '20 at 16:35
  • @Divakar I want the first value in ````val```` to be searched in 1st array of ````arr```` and 2nd value in 2nd ````val```` in 2nd array of ````arr```` . – mArk May 09 '20 at 17:09
  • Is `arr` a list of 3D arrays or a 4D array or a 3D array? – Divakar May 09 '20 at 17:26
  • @Divakar I just updated the question. KIndly check. I want the first value in ````val```` to be searched in 1st array of arr and 2nd value in ````val```` in 2nd slice of arr. – mArk May 09 '20 at 17:27
  • ````arr```` is a list of 3D arrays. – mArk May 09 '20 at 17:29

1 Answers1

1

Given that your values aren't linked in any order we can flatten the array to achieve the desired result:

import numpy as np

arr = np.array([[[1,2,3], [4,5,6], [10,11,12]],
                [[1,2,3], [4,5,6], [7,8,9]]])

vals = np.array([3.2, 6.8])

[arr.ravel()[np.argmin(np.abs(arr.ravel()-v))] for v in vals]
>>> [3, 7]

EDIT

You can loop over each slice in the array to check slice individually:

[a.ravel()[np.argmin(np.abs(a.ravel()-vals[i]))] for i, a in enumerate(arr)]
>>> [3, 13]
Paddy Harrison
  • 1,808
  • 1
  • 8
  • 21