我想通过一个简单的条件对向量进行子集化,并将结果保留在初始向量中:
x = [1,2,3,4,5]
y = 4
x = x[x .< 4]
1 2 3
它工作正常,但如果我有更长的变量名,它看起来像这样:
position = position[position .< 4]
有没有其他更优雅的方法可以做到这一点,而无需在 Julia.js 中输入相同的变量名 3 次。
julia> x = [1,2,3,4,5];
julia> filter!(<(4), x)
3-element Vector{Int64}:
1
2
3
如果您想要使用副本来代替,这会进行就地过滤filter(<(4), x)
。
请注意,该filter!
函数是在这种情况下过滤向量的最快方法。
julia> x = [1,2,3,4,5]
julia> @btime filter!(<(4), $x)
5.500 ns (0 allocations: 0 bytes)
julia> x = [1,2,3,4,5]
julia> @btime $x = $x[$x .< 4];
94.618 ns (3 allocations: 176 bytes)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句