This is something you do not want to do. Why not? because the very next time you ask a question on Answers, it will be a frantic "Why is my code so slow?"
What happens is MATLAB reallocates memory for the entire array, EVERY time you add a new element. Then it must move ALL of your data to the new memory location for the new array. This takes longer and longer on each iteration. It is said to grow quadratically with the size of the array.
This is why we strongly suggest that you PREALLOCATE such arrays with zero (or NaN) elements at the expected final size they will be. Then just stuff each element in one at a time, replacing the zero elements. Personally, I like the idea of using NaNs as the initial elements.
Thus, if you know the final size of your array will be 100, then just do this:
A = NaN(1,100);
for k = 1:100
A(k) = something
end
Now A is never grown with time, and the code will be very fast, with no reallocation problems at all.
1 Comment
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/324329-how-to-use-for-loop-by-adding-the-new-element-in-vector#comment_427709
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/324329-how-to-use-for-loop-by-adding-the-new-element-in-vector#comment_427709
Sign in to comment.