why do we initialize any vector or matrices with zero.
31 Ansichten (letzte 30 Tage)
John D'Errico am 8 Jul. 2023
Bearbeitet: John D'Errico am 8 Jul. 2023
You can preallocate with ANY number. Feel free to preallocate with pi, using say, repmat. Personally, I like to preallocate with NaNs, or maybe the number 17. This way, when I test the code out, I can tell if I screwed up with the size. (What, me screw up? Surely not.)
But you preallocate whenever the array will grow in size otherwise. Read the link proided by @Voss.
Other arrays need not be preallocated.
James Tursa am 9 Jul. 2023
Bearbeitet: James Tursa am 9 Jul. 2023
If you know you will be filling in the variable elements downstream anyway, it would be faster to just allocate the memory and not spend the time filling the values with anything. That being said, MATLAB must have some type of optimizations going on in the background for the zeros( ) function because the timings rival a mex routine that allocates but does not initialize:
>> N = 1024*1024*1024/8 % 1 GB variable
>> timeit(@()uninit(N,1)) % mex routine that allocates but does not initialize
I would point out that this was not the case in earlier versions of MATLAB, where uninit( ) used to handily beat the zeros( ) function.