# for loop is endless

1 view (last 30 days)
Mahmoud Galal on 22 May 2022
Commented: Mahmoud Galal on 25 May 2022
Hello all,
I am trying to create a for loop for 10,000 iterations. I start by creating an empty vector which I then plug in into my for loop. The only problem is my for loop is not stopping and I have to force stop the script to run. Secondly, it seems that my forloop is just overwriting each iteration's computation and not appending it to the next row.
Below is an extract of my code
ST1 = 1:1:10000
%ST1 = zeros()
%Step5: Declaring empty ST2 row vector matrix for 20,000 simulations
ST2 = zeros(1,20000);
%Step5: Simulation of n = 10000 neutral paths
for n = 1:10000
end
%Step6: Compute the discounted cash flow for each path
CST1 = [1:10000]
for n = 1:10000
CST1 = exp(-r*T)*max(ST1(n)-K)
end
##### 2 CommentsShowHide 1 older comment
Mahmoud Galal on 22 May 2022
They are both exhibiting the same problem, I tried to follow the same logic in both. If I fix the 1st one then the 2nd should be a simple corection too. The only good thing about 2nd for loop is that it is not endless but keeps overwriting the result into CST1.

Jan on 22 May 2022
ST1 = zeros(1, 10000); % Pre-allocate
for k = 1:10000
ST1(k) = sadj * exp(r-0.5*(vol^2)) * T + vol * sqrt(T) * randn(k);
% ^^^
end
You need to use and index, if you do not want to overwrite ST1 in each iteration.
Pre-allocation improves the processing speed, because a growing array is very expensive: In each iteration a new array must be created and the contents of the former array is copied.
The most expenvie parts of the calculations are the same in each iteration. so move it before the loop:
ST1 = zeros(1, 10000); % Pre-allocate
C = sadj * exp(r-0.5*(vol^2)) * T + vol * sqrt(T); % Do it once only
for k = 1:10000
ST1(k) = C * randn(k);
end
Mahmoud Galal on 25 May 2022
Hi Jan,
Thanks alot for your input, I have learnt quite a bit from you and indeed reduced the time to run the script. I have managed to modiy my script completley thanks to your help.