In matlab, matrix size can be dynamically changed during execution. When I want to use a matrix to store the result of every iteration, should I create it before step in the loop, or let its size change every iteration? What is the difference?
Asked
Active
Viewed 57 times
0
-
Preallocation is much faster. – zeeMonkeez Feb 12 '16 at 05:42
-
1It is so much faster to preallocate for any matrix of a reasonably large size that the only reason not to do so is if you cannot know the size of your matrix beforehand. That's a good rule to remember. – dgoverde Feb 12 '16 at 07:12
-
this question has a pretty good discussion on preallocation too:[Variable Appears to Change Size on Every Loop Iteration](http://stackoverflow.com/questions/21023171/variable-appears-to-change-size-on-every-loop-iteration-what) – dgoverde Feb 12 '16 at 23:50
1 Answers
1
You should define your matrix beforehand, so matlab can reserve a portion of your computer's memory for it. If you don't preallocate your matrix, each time matlab appends a new row, it'll find a new portion of your computers memory that's big enough for your updated array and move the entire array there.
If you don't know how large your matrix will be beforehand, you can preallocate the first part, say, 1000 rows, and then when you run out of rows you preallocate another 1000 rows. This means that matlab will only have to move the entire array to a new chunk of memory once every 1000 rows. Then when you're done you can just remove the unused rows.

Swier
- 4,047
- 3
- 28
- 52