gpt4 book ai didi

julia - 如何在 Julia 中沿 bool 数组的轴进行按位或归约?

转载 作者:行者123 更新时间:2023-12-01 10:46:20 26 4
gpt4 key购买 nike

我正试图找到在 Julia 中将 3D bool 掩码数组按位或缩减为 2D 的最佳方法。

当然,我总是可以写一个 for 循环:

x = randbool(3,3,3)
out = copy(x[:,:,1])
for i = 1:3
for j = 1:3
for k = 2:3
out[i,j] |= x[i,j,k]
end
end
end

但我想知道是否有更好的方法来减少。

最佳答案

一个简单的答案是

out = x[:,:,1] | x[:,:,2] | x[:,:,3]

但我做了一些基准测试:

function simple(n,x)
out = x[:,:,1] | x[:,:,2]
for k = 3:n
@inbounds out |= x[:,:,k]
end
return out
end

function forloops(n,x)
out = copy(x[:,:,1])
for i = 1:n
for j = 1:n
for k = 2:n
@inbounds out[i,j] |= x[i,j,k]
end
end
end
return out
end

function forloopscolfirst(n,x)
out = copy(x[:,:,1])
for j = 1:n
for i = 1:n
for k = 2:n
@inbounds out[i,j] |= x[i,j,k]
end
end
end
return out
end

shorty(n,x) = |([x[:,:,i] for i in 1:n]...)

timholy(n,x) = any(x,3)

function runtest(n)
x = randbool(n,n,n)

@time out1 = simple(n,x)
@time out2 = forloops(n,x)
@time out3 = forloopscolfirst(n,x)
@time out4 = shorty(n,x)
@time out5 = timholy(n,x)

println(all(out1 .== out2))
println(all(out1 .== out3))
println(all(out1 .== out4))
println(all(out1 .== out5))
end

runtest(3)
runtest(500)

结果如下

# For 500
simple: 0.039403016 seconds (39716840 bytes allocated)
forloops: 6.259421683 seconds (77504 bytes allocated)
forloopscolfirst 1.809124505 seconds (77504 bytes allocated)
shorty: elapsed time: 0.050384062 seconds (39464608 bytes allocated)
timholy: 2.396887396 seconds (31784 bytes allocated)

所以我会选择 simpleshorty

关于julia - 如何在 Julia 中沿 bool 数组的轴进行按位或归约?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25412323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com