Message Boards Message Boards

1
|
5327 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

A simple way for Nearest to operate on multilevel data

Posted 12 years ago
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 this
f[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?
POSTED BY: Vitaliy Kaurov
3 Replies
Thank you, Paritosh and Jeremy, - this is exactly what I needed!
POSTED BY: Vitaliy Kaurov
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 BY: Paritosh Mokhasi
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}}
POSTED BY: Jeremy Michelson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract