Search code examples
matlabvectormatlab-guideindices

MATLAB: Given a row vector, find the indices of two nearest numbers


I had this problem assigned to me in class. I'm still learning MATLAB, so I couldn't figure out how to solve this one using indices. The problem is: Given a row vector of numbers, find the indices of the two closest numbers. For instance:

[index1 index2]=nearestNumbers([2 6 3 13 0 -16.1])
This would output:
index1 = 1
index2 = 3
Since the numbers 2 and 3 in the vector are closer to each other than 
any other pair of numbers

I'm guessing I need to use the find function here (somewhere along the lines of y = find(min()) ) but I'm just not sure how to translate that into a coherent line of code. I tried using the find function I mentioned, but it just gives me a vector row of 0's. Your help would really be appreciated!


Solution

  • Try to get a distance function for each index to every other index.

    for i=1:length(A)
       for j=1:i
          B(i,j)=NaN;
       end
       for j=i+1:length(A)
          B(i,j)=abs(A(i)-A(j));
       end
    end
    
    B =
    
           NaN    4.0000    1.0000   11.0000    2.0000   18.1000
           NaN       NaN    3.0000    7.0000    6.0000   22.1000
           NaN       NaN       NaN   10.0000    3.0000   19.1000
           NaN       NaN       NaN       NaN   13.0000   29.1000
           NaN       NaN       NaN       NaN       NaN   16.1000
           NaN       NaN       NaN       NaN       NaN       NaN
    
    [ind1,in2]=find(B==min(min(B)))
    

    ind1 =

     1
    

    ind2 =

     3