在 Julia 中高效实现 Matlab 的 "Find" 函数

Efficiently implementing Matlab's "Find" function in Julia

我正在尝试在 Julia 中实现 Matlab 的 Find 函数。在Matlab中,代码是

find(A==0)

其中 A 是一个非常非常大的 n x m 矩阵,并且我在大约 500 步的一系列过程中迭代和更新上述内容。在 Julia 中,我通过

实现了上面的内容
[findall(x->x==0, D_tot)[j][2] for j in 1:count(x->x==0,D_tot)]

这似乎工作得很好,除了随着我的迭代进展它变得非常慢。例如,对于第一步,@time yields

0.000432 seconds (33 allocations: 3.141 KiB)

第 25 步:

0.546958 seconds (40.37 k allocations: 389.997 MiB, 7.40% gc time)

第 65 步:

1.765892 seconds (86.73 k allocations: 1.516 GiB, 9.63% gc time)

在每一步中,A 的大小都保持不变,但变得更加复杂,Julia 似乎很难找到零点。有没有比我上面做的更好的方法来实现 Matlab 的“查找”功能?

通过 Matlab 文档我知道你想找到

"a vector containing the linear indices of each nonzero element in array X"

非零意味着 Matlab 表达式中的真实值 A==0

在那种情况下,这可以完成为

findall(==(0),vec(D_tot))

还有一个小基准:

D_tot=rand(0:100,1000,1000)
using BenchmarkTools

运行:

julia> @btime findall(==(0), vec($D_tot));
  615.100 μs (17 allocations: 256.80 KiB)

julia> @btime findall(iszero, vec($D_tot));
  665.799 μs (17 allocations: 256.80 KiB)