Warm tip: This article is reproduced from serverfault.com, please click

search-在Julia中有效地实现Matlab的“查找”功能

(search - Efficiently implementing Matlab's "Find" function in Julia)

发布于 2020-12-01 23:59:20

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

find(A==0)

其中A是一个非常非常大的n×m矩阵,我在大约500步的序列中迭代和更新了上面的矩阵。在Julia中,我通过

[findall(x->x==0, D_tot)[j][2] for j in 1:count(x->x==0,D_tot)]

这似乎工作得很好,除了随着我的迭代进展非常缓慢。例如,第一步,@ time产生

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的“查找”功能?

Questioner
Joshuah Heath
Viewed
11
Przemyslaw Szufel 2020-12-02 08:44:03

仔细阅读Matlab文档,我知道你想找到

“一个包含数组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)