In the performance tips section of the manual, it is recommended to, if 
convenient/possible, pre-allocate the variables used in for-loops in order 
to avoid unecessary allocation and garbage collection.

The example given uses a function xinc(x) which returns a array . Running 
this function in a for loop results in a lot of memory allocation and takes 
significantly more time than the updating version of that same function xinc
!. This is clear to me.

However, if I change the line in xinc(x) to return a float: return [x, x+1, 
x+2] to return x, I notice that the memory use is only 96 bytes, which I 
assume means that no allocation is happening other than the initial one. 
There is no advantage in that case to using the xinc! function. I see that 
the manual suggests that the improvement will only occur with "complex" 
types. Why is that the case?

My other question concerns the necessity of updating functions: why is not 
possible to pre-allocate the variable and use the "normal" function, 
returning its output in the preallocated variable? The space in memory is 
already there, why is it not possible to use it? I believe that this is 
what MATLAB does.

Thanks for your help,
Jeremy

Reply via email to