Showing results for 
Search instead for 
Did you mean: 

Search array for values-ranges (field of values)


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:

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

Are there any other options i could try?
0 Kudos
Message 1 of 6
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

@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
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

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.

Peter Steinberger
0 Kudos
Message 5 of 6
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,

using LV2016/2019/2021 on Win10/11+cRIO, TestStand2016/2019
Message 6 of 6