Use of break statement causing issue

1 view (last 30 days)
TianShu Fan
TianShu Fan on 10 Apr 2019
Answered: Guillaume on 10 Apr 2019
Hi guys, I was doing a simulation of a simplified stock market, and I wanted to store values for both the first time my investment doubled and the end value of my investment after 10 years. I used an if statement with a break command to store the first time of doubling. But after implementing that, my end value reproduced the exact same values for all my simulation runs.
Here is my code: If I comment out the if statement, my code for storing end value works again...
% Initial Investment v_i
v_i=5000;
% Monthly contribution p
p=200;
% Generate random interest rate r
rmin=-0.05;
rmax=0.05;
% Number of month n
n=120;
v=zeros(n,1);
v(1)=v_i;
% Number of simulations s
s=250;
% Storing V120 data
h=zeros(s,1);
% Storing doubled time data
d=zeros(s,1);
for j=1:s
r=rmin+rand(250,1)*(rmax-rmin);
for i=2:n
% if v(i)>=2*v_i
% d(j)=i;
% break
% end
v(i)=(1+r(i))*v(i-1)+p;
end
h(j)=v(120); %PROBLEM if the above if statement is left uncommented
end
hmax=max(h);
hmin=min(h);
disp(hmax)
disp(hmin)
% plot graph for part b
figure(1)
plot(1:n,v)
xlabel("month")
ylabel("investment amount")
title("month vs investment amount")
print('partb.png', '-dpng')
% plot graph for V120 distribution
figure(2)
histogram(h,s)
xlabel("V120 value")
ylabel("occurence")
title("distribution of terminal value of investment")
print('partc2.png', '-dpng')
% c.iii
havg=mean(h);
disp(havg)
hstd=std(h);
disp(hstd)
% c.iv
figure(3)
histogram(d,s)
xlabel("month")
ylabel("occurence")
title("investment doubling time")
print('partc4.png', '-dpng')
Thank you!

Answers (1)

Guillaume
Guillaume on 10 Apr 2019
I'm not sure what you think break does. It completely stops the loop. So, when your code hits break, you stop the i loop and the remaining months never get calculated. You then move to the next j. I don't think that's what you intended.
If you wanted to do something only once in the loop based on some condition, you could use a flag, eg.:
%...
for j=1:s
r=rmin+rand(250,1)*(rmax-rmin);
targetreached = false; %flag
for i=2:n
if v(i)>=2*v_i && ~targetreached
d(j)=i;
targetreached = true;
end
v(i)=(1+r(i))*v(i-1)+p;
end
%...
However, in this case, you really don't need to bother with the test in the loop. You can just get the value at the end of the loop:
for j=1:s
r=rmin+rand(250,1)*(rmax-rmin);
for i=2:n
v(i)=(1+r(i))*v(i-1)+p;
end
d(j) = find(v(i) >= 2*v_i, 1) + 1; %first index of first element whose value is >=2*v_i. That index corresponds to i-1, so add 1.
%...

Community Treasure Hunt

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

Start Hunting!