[英]Efficiently return the index of the first value satisfying condition in array
[英]Find index of maximum element satisfying condition (Julia)
在 Julia 我可以使用argmax(X)
來查找最大元素。 如果我想找到所有滿足條件C
的元素,我可以使用findall(C,X)
。 但是我怎樣才能將兩者結合起來呢? 在 Julia 中找到滿足某些條件的最大元素索引的最有效/慣用/簡潔的方法是什么?
根據我對您的問題的了解,您可以使用findmax()
(需要 Julia >= v1.7)來查找findall()
結果的最大索引:
julia> v = [10, 20, 30, 40, 50]
5-element Vector{Int64}:
10
20
30
40
50
julia> findmax(findall(x -> x > 30, v))[1]
5
上述function的性能:
julia> v = collect(10:1:10_000_000);
julia> @btime findmax(findall(x -> x > 30, v))[1]
33.471 ms (10 allocations: 77.49 MiB)
9999991
更新: @dan-getz 建議的使用last()
和findlast()
的解決方案比findmax()
() 表現更好,但findlast()
是贏家:
julia> @btime last(findall(x -> x > 30, v))
19.961 ms (9 allocations: 77.49 MiB)
9999991
julia> @btime findlast(x -> x > 30, v)
81.422 ns (2 allocations: 32 bytes)
如果您想避免分配,懶惰地過濾數組會起作用:
idx_filtered = (i for (i, el) in pairs(X) if C(el))
argmax(i -> X[i], idx_filtered)
不幸的是,這大約是手寫版本的兩倍(在我的測試中):
function byhand(X, C)
start = findfirst(C, X)
(start == nothing) && return nothing
imax, max = start, X[start]
for i = start:lastindex(X)
if C(X[i]) && X[i] > max
imax, max = i, X[i]
end
end
imax, max
end
您可以存儲findall
返回的索引,並使用滿足條件的向量的argmax
結果對其進行子集化。
X = [5, 4, -3, -5]
C = <(0)
i = findall(C, X);
i[argmax(X[i])]
#3
如@August的答案所示,更快的方法是循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.