suppose I have an existing array like
x = rand(4)
and then I want to reset x
to zero. Can I avoid doing x = zeros(4)
. I'm concerened about memory allocation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With