Allocation
MatLab will automatically resize matrices as needed when you use larger and larger indices in your code.
This feature is very convenient but also very time expensive!
(see Preallocation
in the MatLab Docs)
Sometimes pre-allocating the size of your matrices can speed up significantly your code.
You can use the tic and toc commands to evaluate the time that
the CPU spent in some segment of your program.
E.g. run the following code, once with and once without the second line.
N = 100000
f=zeros(1,N);
tic
f(1)=1;
for i=2:N
f(i)=f(i-1)+i;
end
rt=toc;
fprintf('f(%d)=%g, time spent in the cycle = %g s',N,f(N),rt);