## 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.

on 01 Feb 2007 at 1:01 pmCruchonSomething 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.

on 01 Feb 2007 at 1:08 pmLawrence Davidi believe that’s exactly what i wrote above.

on 29 May 2007 at 10:28 amRomanThanks guys!

on 20 Jul 2007 at 4:00 pmHilikus??? that returns the difference between the closest and the target vale not its INDEX

on 20 Jul 2007 at 4:13 pmlawrencehilikus:

the second argument returned is the index; the first argument returned is the difference.

on 20 Jul 2007 at 4:21 pmHilikusBah, nevermind, i didnt see the double output

on 15 Sep 2007 at 10:18 amD>> [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

on 29 Feb 2008 at 2:58 pmjessI love you for this! *mwah*

on 05 Mar 2008 at 12:44 pmhuzzzaathanks guys!!!!!!!!! saved me hours developing my own algorithm!

on 28 May 2008 at 12:43 pmChanMan, you guys really rock! Thanks a lot, saved me hours. Keep up the good work!!

on 27 Aug 2008 at 12:01 pmmarchessouxThanks a lot, exacty what I needed, so economy of many time ;=)

Cédric

on 23 Sep 2008 at 11:44 amdavecan you do something similar but for several k’s at a time?

on 04 Dec 2008 at 2:23 amMoneyGIs there a similar way to get position information out of a matrix.

I tried something like,

[row,col]=min(min(matrix))

but that returns only the final row that the element is in, not its exact location.

on 26 Dec 2008 at 5:50 pmDen Wald vor lauter Bäumen nicht sehen … « wAnNaBe NeRd[...] to see the wood for the trees”. I guess it is also know to non-German speakers? I just found this very trivial, banal and easy Matlab command line, which makes my equivalent lines look very stupid and [...]

on 17 Feb 2009 at 4:02 amTomNice! Saved me some time!

on 11 Mar 2009 at 5:29 amSameerHow Matlab search the object or variable name in simulink model.

mean Functionality of Edit->Find…(Ctrl+F).

on 11 May 2009 at 12:03 pmcatobut what if you want to be sure you at the value closest to this value right/left side?

for instance, a cumulative probability vector and you want to find the index for the value that is the first above 0.5?

on 22 Aug 2009 at 2:59 pmefraingreato!

thanks a lot!

on 27 Aug 2009 at 1:33 pmsharkeyThanks for post this! You just made my life easier.

on 27 Aug 2009 at 1:35 pmsharkeyapparently, the space this took in my brain was previously occupied by my knowledge of the English language… sorry.

Thanks for posting this. You just made my life easier.

on 21 Nov 2009 at 6:53 pmpenguinyou could use something like this for multiple ‘k’s (‘range’ == ‘a’, ‘vector’ is a set of ‘k’s):

function inds = findClosest(range, vector)

% ‘flatten’ everything into row vectors

origshape = size(vector);

sz_r = size(range);

numTargets = sz_r(1) * sz_r(2);

numInputs = origshape(1) * origshape(2);

range = reshape(range, [1, numTargets]);

vector = reshape(vector, [1, numInputs]);

% find the difference between the target values and the actual values

% ‘range’ is replicated across columns,

% ‘vector’ is replicated across rows

diff = repmat(range’, 1, numInputs);

diff = diff – repmat(vector, numTargets, 1);

diff = abs(diff);

[vals, inds] = min(diff);

inds = reshape(inds, origshape);

end

on 09 Mar 2010 at 5:11 amMaxMuch better than my routine, which always

gets confused by the extrema of the array.

And faster too, love it.

on 28 May 2010 at 6:53 amMultiple output arguments « Abandon MATLAB[...] why multiple output arguments in Matlab were a poor design decision. But here is a start. In an unsuccessful attempt to find a code that’s less than O(N*M) in storage for a problem that in a…, I saw that someone on Yahoo! Answers wants to know, Is there a similar way to get position [...]

on 10 Aug 2010 at 3:04 pmJay MungHey Lawrence. Columbia BME ’04 alum here. I googled for your little trick here and was pleasantly surprised to find your blog. Keep up the good work.

Jay

on 23 Aug 2010 at 11:54 amAlexanderLawrence, I really enjoy your blog, I have found useful answers to many questions. This one was not the exception. Thanks a lot and keep up the great work.

on 27 Sep 2010 at 4:39 pmdavieThis was a fantastic hint. Simple and effective. Saved me hours of trying to bin data for use in a data averaging algorithm. Glad to see being clever is working out for you. Thanks!

on 08 Oct 2010 at 11:06 amMattThis is a great tip thanks.

I did have one problem with it though, in an unlikely scenario. I was using it in my code when a could be only one value (ie, len(a) = 1) when this is the case MATLAB does not like it when the ‘min’ function is only working on one value and returns an error (??? Index exceeds matrix dimensions.)

I fixed it in my code by placing an ‘if’ statement to check to see that the length of ‘a’ is more than one. Is anybody aware of a simpler method of solving this problem??

thanks,

Matt

on 08 Oct 2010 at 11:56 amMattoops, no, ignore my message. I’m an idiot, the problem was, that I errenously had created a variable called ‘min’ in my code previously and matlab was calling that variable instead of the min function.

on 13 Mar 2011 at 1:21 pmgabusHi gays,

I’ve had the same problem several times in my research, so I’ve developed a function to get the index “index” associated to the closest value to “value” closest element in “freqVect” .

Hope you gays find it useful!!

———————————

function index = getFreqIndex(freqVect,value)

% Esta funcion busca dentro de un vector con valores no necesariamente igualmente espaciados

% y devuelve el indice mas cercano del vector que corresponde al valor “value”.

% El resultado se da dentro de una banda de precision de la forma [value-df1,value+df2].

% Ojo, el vector no puede tener valores repetidos.

index=-1;

for i=1:length(freqVect)

switch(i)

case 1

df1=0;

df2=abs(freqVect(i)-freqVect(i+1))/2;

case length(freqVect)

df1=abs(freqVect(i)-freqVect(i-1))/2;

df2=0;

otherwise

df1=abs(freqVect(i)-freqVect(i-1))/2;

df2=abs(freqVect(i)-freqVect(i+1))/2;

end

if(freqVect(i)>=value-df1 && freqVect(i)freqVect(length(freqVect))), index=length(freqVect);end

if(value<freqVect(1)), index=1;end

end

end

on 14 Mar 2011 at 1:32 pmNipunfor finding the exact location of any data in the array (both the row and column)

try this

[I,J] = find(T==max(max(T)))

where T is the array.

on 23 Mar 2011 at 8:37 pmRabindra Rimalgreat8 (°_°)!

thanks a lot!

i had spend more then 10hrs for it.

thank you soo much.

<3 <3

on 25 Jul 2011 at 7:44 pmKelzHi, I have a very large matrix, i have the matrix index (x,y,z) but im intrested in the actual value of this index in the original array. How do I go about this?

on 25 Jul 2011 at 7:45 pmKelzHi, I have a very large matrix, i have the matrix index (x,y,z) but im intrested in the actual value of this index in the original array. How do I go about this? Kelz

on 10 Aug 2011 at 5:32 pmKostasWorked brilliant, thanks!

on 03 Sep 2011 at 12:45 pmbasuhow to find proximity matrix of binary data?

and how to find angle for bounding boxes of binary image using PCA

on 30 Nov 2011 at 12:03 pmMicheleHi!

I need to find a value in different Array(n,m).

I try to use something like this:

[n,m]=find(A47==9941005309)

and this works well, so i need a loop that for i=1:47 searchs 9941005309 in A1, A2, Ai…

I tried like this:

[n,m]=find(R,num2str(l)==9941005309)

where R=’A’ but it doesn’t work, where I’m wrong?

Thanks for help me!

on 08 Dec 2011 at 9:14 pmBrianFor multidimensional matrices:

[i,j,k] = closest_match(M,a)

% Find the indices of the value closest to a in matrix M

[~, linear_index] = min(abs(T(:)-val)));

[i,j,k] = ind2sub(size(T),linear_index)

on 08 Dec 2011 at 9:16 pmBrianEdit to above; I forgot to type “function”

function [i,j,k] = closest_match(M,a)

on 20 Jan 2012 at 8:00 pmParisWhat if I need the closest entry of the array but within limits?

Example to clarify:

I have the array test=[5,6,7,8,9,10] and I want the index of the entry closest to 5 out of the entries that are >=6 (therefore the index of 6 -> 2).

[~,idx]=min(abs(5-test)) returns 1 of course…

At first I though about trying something like

[~,idx]=min(abs(5-test(test>=6)))

but it won’t do since 6 has idx=1 within the test(test>=6) array and therefore the ans is still idx=1.

Any ideas?

on 14 Jun 2012 at 5:59 pmmariamif i add to images in matlab and the result is a greater than 255 ,or when i subtract two image and the result is smaller than 0

what is the matlab do in this cases i need to now becouse i will implement it in CUDA

on 22 Aug 2012 at 10:39 pmAminthat is a great tip, thanks

on 20 Oct 2014 at 2:47 pmAnother WorldAnother Worldin matlab, find the array position of an entry closest to some arbitrary value » from the desk of stinkpot

on 05 Nov 2014 at 1:38 pmRising Artist: Elan NoelleRising Artist: Elan Noellein matlab, find the array position of an entry closest to some arbitrary value » from the desk of stinkpot

on 16 Jun 2015 at 5:54 amwww.motpanels.comAmazing factors listed here. I will be extremely content to view your content πανελ πετροβαμβακα. Many thanks that i’m having a look in front to feel an individual. Will you be sure to fall me a mailbox?

on 01 Feb 2016 at 12:30 amHasibpenguin, you are a genius. Your function is awesome.

on 04 Feb 2016 at 7:33 amRahulHi,

i have two arrays in which one derived from other as,

A=[2,3,4,5,6,7];

B=[4,5,7];

i need some what like this,

C=[0,0,4,5,0,7];

how is this possible.please help me!.

Thanks