Pre-allocating Space

Raheelanjum
2 min readDec 12, 2024

In Matlab, arrays are dynamic in size, meaning whenever you need a larger array, you can just index based on this larger number, and Matlab will automatically resize your original array to be the new, bigger size. There is a cost to doing this, which is that your program will slow down if you do it often enough. Thus, if you know (or have a good guess) at how big the array needs to be in the first place, you can "pre-allocate" it, meaning pre-size the array.

Pre-Allocating Space for an Array

If you know approximately how big an array will be when your program is done, you can ask Matlab to give you an "empty" array of that size to begin with. This will make your program much faster for large data sets. It will have almost no effect on small data sets.

To pre-allocate an array (or matrix) of numbers, you can use the "zeros" function. To pre-allocate an array (or matrix) of strings, you can use the "cells" function.

Here is an example of a script showing the speed difference. Make sure you "clear" the array variable if you try the code more than once.

For your likely programming purposes, less than 10000 is likely to be "small," and greater than 10000 is likely to be "large." These numbers will change based on how much memory your computer has, NOT on how fast your computer is!

--

--

Raheelanjum
Raheelanjum

Written by Raheelanjum

Highly skilled and experienced content writer dedicated to crafting compelling, informative content that resonates with diverse audiences. Expertise spans blog

Responses (11)