matlab cody学习笔记 day19

三月的第三天,眼睛疼

(1)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

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

通过获取每个索引与其他索引的距离,构造一个距离矩阵。

答:

function [index1 index2] = nearestNumbers(A)

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

[index1 index2]=find(B==min(min(B)));

答:

function [index1 index2] = nearestNumbers(A)

index1 = 1;

n=length(A);

index2 = n;

dx=abs(A(1)-A(n));

for i = 1:n

for j = i+1:n

now=abs(A(i)-A(j));

if now<dx

index1=i;

index2=j;

dx=now;

end

end

end

end

第二个答案就比较符合正常的比较逻辑

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值