1

I've written the following function:

import numpy as np


def _find_nearest(array, value):
    """Find the index in array whose element is nearest to value.

    Parameters
    ----------
    array : np.array
      The array.

    value : number
      The value.

    Returns
    -------
    integer
      The index in array whose element is nearest to value.

    """
    if array.argmax() == array.size - 1 and value > array.max():
        return array.size
    return (np.abs(array - value)).argmin()

I'd like to vectorize this function, so that I can pass several values at once. That is, I'd like to have value be an array, and have _find_nearest return, rather than a single index, the indices for each of the values in the submitted value_array.

Can anyone see a way to do this?

abcd
  • 10,215
  • 15
  • 51
  • 85
  • 1
    Add another dimension (```np.newaxis```) to the array being searched then broadcast across the new dimension. – wwii Aug 13 '16 at 02:31
  • 1
    Given huge arrays, broadcasting might waste a lot of memory with repeated data. – Kartik Aug 13 '16 at 02:38
  • 1
    @Kartik, 'waste' is pretty subjective, how about consume. Sometimes you trade time for space and space for time. – wwii Aug 13 '16 at 03:14
  • Consume it is. I agree with you. – Kartik Aug 13 '16 at 03:18
  • See if this helps : [`Find elements of array one nearest to elements of array two`](http://stackoverflow.com/questions/37841654/find-elements-of-array-one-nearest-to-elements-of-array-two). – Divakar Aug 13 '16 at 05:58

1 Answers1

1

Inside the parent function, where both the value and the array are visible, you can use a lambda to enable the vectorization. I shall call the parent function main

def main():
    value = np.random.rand(10, 1)
    array = np.random.rand(100, 100)
    vec_nearest = lambda x: _find_nearest(array, x)
    np.vectorize(vec_nearest)(value)

This will work on one array, and multiple values of vector. The return will be an array.

Kartik
  • 8,347
  • 39
  • 73