【MATLAB编程实例练习】-(33)寻找数组最近的数(Nearest Numbers)

题目

来源于Mathwork上的Cody,Problem 29 - Nearest Numbers.

Given a row vector of numbers, find the indices of the two nearest numbers.
Examples:
[index1 index2] = nearestNumbers([2 5 3 10 0 -3.1])

index1 =
1
index2 =
3

[index1 index2] = nearestNumbers([-40 14 22 17])

index1 =
2
index2 =
4
Notes
The indices should be returned in order such that index2 > index1.
There will always be a unique solution.

代码

function [index1,index2] = nearestNumbers(A)
for i=1:length(A)-1
    [M,I]=min(abs(A(i)-A(i+1:end)));
    B(i,1)=i;
    B(i,2)=I+i;
    B(i,3)=M;
end
[~,I]=min(B(:,3));
index1=B(I,1);
index2=B(I,2);
end

其它优秀代码

function [index1 index2] = nearestNumbers(A)
[sorted sort_ind] = sort(A);
[~,min_ind] = min(diff(sorted));
sort(sort_ind(min_ind:min_ind+1));
index1 = ans(1);
index2 = ans(2);
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值