# A simple way for Nearest to operate on multilevel data

Posted 11 years ago
4106 Views
|
3 Replies
|
4 Total Likes
|
 I need some help with simplification of a function. Nearest can be very handy, but does not have level specification. My problem is simple. I have the following data consisting of integers and binary vectors: dat = Table[{RandomInteger[100], RandomInteger[1, 15]}, {10}]; dat // Column  Out[] =  {{21, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1}}, {15, {1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0}}, {55, {0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0}}, {79, {1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1}}, {55, {1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1}}}I also have a test vector:tst = RandomInteger[1, 15]Out[] = {1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0}I need to find a vector in my data nearest to test and return it and its corresponding integer. If several solutions exist I take the first one. I came up with thisf[dat_, tst_] := First[Extract[dat, Position[#, First[Nearest[#, tst]]] &[dat[[All, 2]]]]]f[dat, tst]Out[] = {15, {1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0}}Which works but feels rather convoluted. Can anyone suggest an alternative solution?
3 Replies
Sort By:
Posted 11 years ago
 Thank you, Paritosh and Jeremy, - this is exactly what I needed!
Posted 11 years ago
 You can have Nearest give you the index of the data that matches the test. In[59]:= dat = Table[{RandomInteger[100], RandomInteger[1, 15]}, {10}];  In[64]:= test = RandomInteger[1, 15]  In[69]:= nf = Nearest[dat[[All, 2]] -> Automatic] ;  In[68]:= dat[[nf[test]]]  Out[68]= {{61, {1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}}}
Posted 11 years ago
 Nearest is eactly what you want. In[43]:= f = Nearest [#[[2]] -> # & /@ {{21, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1}}, {15, {1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0}}, {55, {0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0}}, {79, {1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1}}, {55, {1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1}}}]  In[46]:= f[{1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0}, 1][[1]] Out[46]= {15, {1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0}}