当前位置: 首页 > 工具软件 > Cody > 使用案例 >

matlab cody学习笔记 day19

蔚元明
2023-12-01

三月的第三天,眼睛疼

(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

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

 

 类似资料: