0

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!

4

2 回答 2

2

没有循环,只是bsxfun

>> B = abs( bsxfun(@minus, A, A' ) ); %//'
>> B( 1: (numel(A)+1) : end ) = inf; % ignore zeros on diagonal
>> [ii jj] = find( B == min(B(:)) );
于 2013-07-07T18:58:16.023 回答
-1

尝试为每个索引获取每个其他索引的距离函数。

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
于 2013-07-07T18:55:55.733 回答