You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia如何获取向量内前n个最小值的对应索引并对比结果

Julia 获取最小n个值对应原始索引的实现

你可以改用sortperm函数,它会返回排序后对应的原始数组索引,同样支持部分排序参数,调整后的代码如下:

function smallestn_indices(distance, n)
    # 返回最小的n个值对应的原始1基索引
    return sortperm(distance; alg=Sort.PartialQuickSort(n))[1:n]
end

效果验证

用你提供的示例数据测试:

distance = [1, 5, 6, 7, 8, 9, 10, 2, 3, 4]
distance_1norm = [1, 8, 6, 7, 8, 9, 10, 2, 3, 4]

# 取最小5个值的索引
distance_idx = smallestn_indices(distance, 5)
distance_1norm_idx = smallestn_indices(distance_1norm, 5)

输出结果完全匹配预期:

  • distance对应索引:[1, 8, 9, 10, 2],即第1位、第8位、第9位、第10位、第2位
  • distance_1norm对应索引:[1, 8, 9, 10, 3],即第1位、第8位、第9位、第10位、第3位

如果需要同时获取最小n个值和对应索引,可以调整函数一次性返回两个结果:

function smallestn_with_indices(distance, n)
    idx = sortperm(distance; alg=Sort.PartialQuickSort(n))[1:n]
    return distance[idx], idx
end

内容的提问来源于stack exchange,提问作者Bennett.tai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:45:05