While this may not be an important optimization for small data sizes (such as 1-by-100), it can be a significant improvement if the size of the data is large. function data = fillDataWithPreallocation In this version of the function, there will only be a single memory allocation and the values of data never have to be copied from one location to another. In this example we know that the final size of the variable data is 1-by-100, so we can easily fix the issue by preallocating the variable with the zeros function. It also has the effect of increasing peak memory usage, since the old and new copy must both exist for a period of time. This memory allocation and copying of values can be very expensive in terms of computation time. After reallocating memory, MATLAB has to copy the old values to the new memory location. MATLAB will reallocate memory numerous times while executing this loop. The function returns the variable data after assigning to it, one element at a time. Imagine we write the following small function to fetch our data from some external source. While we will quickly review the topic of preallocation here, readers unfamiliar with this topic are encouraged to read some of the provided links. There are numerous resources that discuss preallocation, such as sections of our documentation and articles discussing improvements to MATLAB allocation strategies.
#Allocate null vector matlab code
The Code Analyzer and the MATLAB Editor.