From: Phrogz Date: 2009-11-22T23:45:55+09:00 Subject: Re: Finding the closest value from a matrix On Nov 21, 1:04 pm, Mahadev Ittina wrote: > I have a matrix that looks something like this > >        85        90       100       125        150         175 > 8     1.183    1.118     1.006     0.805      0.671      0.575 > 10    1.847    1.744     1.57      1.256      1.047      0.897 > 12    2.659    2.511      ..        ..           ...        ... > 16    ...       ...        ..     ...           ...        .. > > Say, I have a value of 1.1, I want it to automatically choose the > closest bigger value i.e. 1.118 and say 8 mm diameter at 90 mm spacing. > How can this be implemented? I thought of creating hashes. but it seems > too complicated. If anyone is wondering about the formula it goes like > this. Create a one-dimensional array where each entry records the value, row and column number (or row and column headers). # This should be programmatically done by iterating your array # not explicitly as I'm showing it here. Descriptor = Struct.new :row, :col, :value a = [ Descriptor.new(0, 0, 1.183), Descriptor.new(0, 1, 1.118), Descriptor.new(0, 1, 1.006), # ..etc. ] # Sort the array by value a = a.sort_by{ |desc| desc.value } # Create a method that finds the closest (larger) value in the array # via a binary search: http://en.wikipedia.org/wiki/Binary_search # (Left as an exercise for the reader.) # Now you know what row and column it came from.