如何找到最小距离

时间:2017-11-28 12:31:46

标签: arrays matlab sorting

我有一个代表8个距离的矢量:

distance=[6.5 2.5 6.2 3.01 4.7 4.03 5.09 5.09];

我想只保留此向量的2个最小距离。

为此,我使用

[sort_dist index] = sort(distance);
Two_minimal_distance = sort_dist(1:2);

但要找到2个最小距离的索引而不对矢量进行排序?

1 个答案:

答案 0 :(得分:3)

您可以按照以下方式执行此操作。结果是1×2向量ind

  • 如果您想要两个最小条目的索引,即使它们具有相同的值

    distance=[6.5 2.5 6.2 3.01 4.7 4.03 5.09 5.09]; % data
    tmp = distance; % copy of data. Will be overwritten
    [~, ind] = min(tmp); % index of minimum value
    tmp(ind) = NaN; % overwrite with NaN, so the subsequent call to min will ignore it
    [~, ind(2)] = min(tmp); % index of second-minimum value
    
  • 如果您希望(第一次出现)两个最小唯一值的索引:

    distance=[6.5 2.5 6.2 3.01 4.7 4.03 5.09 5.09]; % data
    tmp = distance; % copy of data. Will be overwritten
    [val, ind] = min(tmp); % value and index of minimum value
    tmp(tmp==val) = NaN; % overwrite all occurrences of that value
    [~, ind(2)] = min(tmp); % index of second-minimum unique value