what's the fastest way to reset a julia array to all zeros?
The best way to do it in one line is:
x .= zero(y)
or
fill!(x, zero(y))
where y
is the type of number you want it to be like. The reason why this way is good is that it works in all cases. If x
is any type, using this will work as long as y
matches the type (indeed, you can use y = x[1]
).
When I mean any type, I mean that this also works for odd number types like SIUnits. If you use this command, a package could support SIUnits without ever having to import the package since this will apply the correct units to the x
values (as long as all of its operations are correct in units), while fill!(x, 0.0)
will error due to wrong units (you can also use fill!(x, zeros(y))
. Otherwise, you'd have to check for units and all sorts of things.
You can do
fill!(x, 0.0)
This overwrites the contents with zeros.
This should be just as efficient as just doing a for
loop, though:
for i in 1:length(x)
x[i] = 0.0
end
Indeed, if you do @edit fill!(x, 0.0)
, you will see that this is basically what it is doing (except that it uses @inbounds
for more efficiency).