How to run a while loop 1000 times
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Yifei Yang
am 17 Okt. 2022
Kommentiert: Torsten
am 18 Okt. 2022
Here is my matlab code, I try to run this while loop 1000 times, but i have no idea how to do it.
Could you give me some ideas abouut it.
T = 400;
x = 150; %initial amount of money.
xx = [150]; tt = [0];
tstart=0;
ev_list = inf*ones(3,2); %record time, type
ev_list(1,:) = [7 + 3*rand, 1]; %schedule type 1 event
ev_list(2,:) = [25 + 10*rand,2]; %schedule type 2 event
ev_list(3,:) = [-log(rand),3];
ev_list = sortrows(ev_list,1);
for i = 1:1000
t=tstart
while t < T
t = ev_list(1,1);
ev_type = ev_list(1,2);
switch ev_type
case 1
x = x + 16*-log(rand);
ev_list(1,:) = [7 + 3*rand + t, 1];
case 2
x = x + 100;
ev_list(1,:) = [25 + 10*rand + t, 2];
case 3
x = x - (5 + randn);
ev_list(1,:) = [-log(rand) + t, 3];
end
ev_list = sortrows(ev_list,1); % sort event list
xx = [xx,x];
tt = [tt,t];
end
XX{i} = xx;
TT{i} = tt;
xx = [];
tt = []; % reset t to a value < T
end
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
John D'Errico
am 17 Okt. 2022
You use a for loop when you know how many iterations you will need. So I'm not sure why you want to use a while loop for a specific number of iterations. The point being, using a while loop with a counter takes more work. Why would you want to do more work? So...
for i = 1:1000
stuff
end
As opposed to something qualitatively like this:
counter = 1;
while counter <= 1000
stuff
counter = counter + 1;
end
So not too much more work, but now you need to maintain the counter, to test for when you are done. You need to be careful about making sure the loop terminates properly. Should you have incremented the counter immediately after the while, or at the end? (Note that sometimes you might do it in one place or the other, and then you need to be careful, else your code might terminate at the 999th iteration, or go one too far, etc. This is the stuff bugs are made from.)
The foor loop is easier to visualize, to recognize that the loop will continue for exactly 1000 iterations, etc. The for loop makes for better code here. Good code is easy to read, easy to follow, easy to debug, easy to maintain.
Use a while loop mainly when you don't know when the loop will terminate.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!