我在课堂上把这个问题分配给了我。我还在学习MATLAB,所以我无法弄清楚如何使用索引来解决这个问题。问题是:给定一个数字的行向量,找到两个最接近的数字的索引。例如:
[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
我猜我需要在这里使用find
函数(在y = find(min())
的某处),但我不确定如何将其转换为连贯的代码行。我尝试使用我提到的find函数,但它只给了我一个0的向量行。非常感谢您的帮助!
答案 0 :(得分: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(:)) );
答案 1 :(得分:-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