# LabVIEW

cancel
Showing results for
Did you mean:

## Search array for values-ranges (field of values)

Hi,

i´ve got some problems with finding values in an array which does not exactly have the same value.
I need a function to look for the best appoximation of a value in an array.

For example:

array:
4,568|a I´m looking for 4,75 --> He should give me the index of 4,775.
4,775|c
4,889|d

Are there any other options i could try?
Message 1 of 6
(2,582 Views)

## Re: Search array for values-ranges (field of values)

Go over the array in a auto-indexing for loop and calculate the difference between each element and your target. Keep the resulting element and its index in a shift register. If the difference for the current element is smaller than for the one in the shift register, put the current element in the shift register. When the loop is over, the element in the SR is the one closest to your target.

If the array is sorted you can use a while loop to stop after a certain point. If it's very big you can try sorting it and then using the while loop. You will have to experiment to see if it's faster.

___________________
Try to take over the world!
Message 2 of 6
(2,576 Views)

## Re: Search array for values-ranges (field of values)

@Peter Steinberger wrote:
Are there any other options i could try?

Apologies if I'm missing something, but if it's a sorted 1D array, would the "Threshold 1D Array" function work for you? Just round the returned fractional index to nearest and that's the index of interest.
=====================================================
Fading out. " ... J. Arthur Rank on gong."
Message 3 of 6
(2,565 Views)

## Re: Search array for values-ranges (field of values)

If you function is always increasing, Threshold 1D array (in the array palette) will do what you want. You will get the fractional index. Since you want the nearest integer index, use "round to nearest".

(If you function is always decreasing, Invert the array first. If the function goes up and down, things get more complicated because there will be more than one solution. Still, it can be solved :))
Message 4 of 6
(2,564 Views)

## Re: Search array for values-ranges (field of values)

Hi,

thank you all for the hints. I´ll try the "treshold" variant first.

I´m really surprised so many people answered and that they have done it this way fast. I haven´t seen something like that before.

greetings,
Peter Steinberger
Message 5 of 6
(2,550 Views)

## Re: Search array for values-ranges (field of values)

Hello Peter,

if you can afford the memory (that is: your arrays aren't that big...) you can do this without a for loop:
array - (value to search for) -> absolute value -> array min/max -> min index
Best regards,
GerdW

using LV2016/2019/2021 on Win10/11+cRIO, TestStand2016/2019
Message 6 of 6
(2,544 Views)