Preallocating a vector, what is the correct way?

22 views (last 30 days)
Hi
Trying to learn how to do preallocation to save on memory, I copy pasted the example code from the help page into the editor.
x = zeros(1, 1000000);
for k = 2:1000000
x(k) = x(k-1) + 5
end
This is advertised as taking 0.011938 seconds or some such.
Upon running this code, the output is a massive quantity of zeros, that as of ten minutes afterwards, is still being produced. (it looks to me as if it's writing out a million zeros a million times) What is wrong with this code and how do I correct it?
Also, how do I terminate a process within matlab without shutting down the entire thing? It just keeps on going!

Accepted Answer

Guillaume
Guillaume on 7 Oct 2014
1. Preallocation does not save any memory. It will save time
2. Put a semicolon at the end of your x(k) = x(k-1)+5 line and it'll process it near instantly:
x(k) = x(k-1)+5;
The reason it's so slow is because of the lack a semicolon, matlab prints the whole matrix (1 million numbers) at each iteration of the loop.
3. To terminate a running calculation or script, press CTRL + C

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!