in matlab, find the array position of an entry closest to some arbitrary value
March 4th, 2006 by Lawrence David
a friend asked:
matlab question: i have an array of data. how do i get matlab to find the position of an entry closest to some arbitrary value?
for instance, i would have
a= [1; 4; 6; 8; 12]
i want to search for 9 and have matlab spit back 4, the entry in a closest to 9.
here’s one way to solve that problem (assuming that variable k=9):
>> [min_difference, array_position] = min(abs(a - k))
wheree array_position is the desired index value.
Something like
[rte,index]=min(abs(X-x0)); where x0 is the target and X is the array you want to search in works. The answer is index.
i believe that’s exactly what i wrote above.
Thanks guys!
??? that returns the difference between the closest and the target vale not its INDEX
hilikus:
the second argument returned is the index; the first argument returned is the difference.
Bah, nevermind, i didnt see the double output
>> [trash array_position] = min(abs(a - k))
probably should have a “,” or odd things may happen.
[trash, array_position] = min(abs(a - k))
I wasted a lot of time recently and that simple problem caused it.
D
I love you for this! *mwah*
thanks guys!!!!!!!!! saved me hours developing my own algorithm!
Man, you guys really rock! Thanks a lot, saved me hours. Keep up the good work!!
Thanks a lot, exacty what I needed, so economy of many time ;=)
Cédric
can you do something similar but for several k’s at a time?