for loop is endless
1 view (last 30 days)
Show older comments
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
ST1 = sadj*exp(r-0.5*(vol^2))*T+vol*sqrt(T)*randn(n);
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
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!