Announcement

Collapse
No announcement yet.

finding the closest number in an array

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • finding the closest number in an array

    Hello,

    I'm trying to use a 18f2682 to search an array of 330 words for the closest match, and return the element number. Can anyone share a snippet of code?

    Thanks,

    Bruce



  • #2
    When you say "word", I assume you mean a 16 bit value, not an ASCii array.


    For just a few choices, you could use the SELECT CASE routine. I found difficulties when the choices get too large. I don't think 330 words will fit on a single page in the memory. You might break it down into ranges with SELECT CASE where the first SELECT CASE directs to a subroutine, then from the subroutine you select the specific value. Something like this:

    SELECT CASE Var
    CASE IS < 10 : GOSUB LowValue1
    CASE IS < 20 : GOSUB LowValue2
    ............
    CASE IS < 320 : GOSUB HighValue5
    CASE ELSE : GOSUB HighValue6
    END SELECT

    LowValue1:
    SELECT CASE Var
    CASE IS 1 : GOSUB DoSomething
    Etc.
    We can crack this cotton PIC'n thang!

    Comment


    • #3
      Thank you. I ended up using this.... it's not elegant (and it does not consider negative results.... but the array is sequential).

      curr = 5000

      for i = 0 to 329

      T5= ypos - value(i) 'T5 is temp variable, Y Pos is the ADC value, value(I) is the array, pointer is the array element number
      If T5 > 0 and t5 < curr Then
      curr = value(i)
      pointer = i
      Endif

      Comment

      Working...
      X