Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the fastest way to reset a julia array to all zeros?

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.

like image 796
Florian Oswald Avatar asked Sep 19 '16 12:09

Florian Oswald


1 Answers

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.

like image 52
Chris Rackauckas Avatar answered Oct 14 '22 16:10

Chris Rackauckas