loop problem with time delay

4 Ansichten (letzte 30 Tage)
Hayden O'Neil
Hayden O'Neil am 5 Okt. 2017
Beantwortet: DUY Nguyen am 2 Mär. 2023
Write Matlab code using a loop structure that displays the following text to the command window: “Man, I am getting older and wiser by the second” And (after a carriage return) on the following line displays the phrase: “and now I am 1 second older”
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 2 seconds older” [Note that I want you to update the units on “second” to show correct number –second(s) ]
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 3 seconds older”
And so on and so on until 10 full carriage returns of textual display have been reached and the final line reads: “and Prof. Koz just wasted approximately blank seconds of my life”
I have no idea how to do this problem or delay output by one second for each line.

Akzeptierte Antwort

James Tursa
James Tursa am 6 Okt. 2017
Bearbeitet: James Tursa am 6 Okt. 2017
Hint: You could use tic and toc for this. Start your code with a tic statement. Then you can examine the toc result in a loop and take appropriate action (display a message, break out of the loop, etc). The toc result will be in seconds. E.g., experiment with the following code and see if you can modify it to do what you want.
time_delay = 5;
tic
while( true )
if( toc >= time_delay )
fprintf('It has been %f seconds\n',time_delay);
break;
end
end
Alternatively, you could look into using the pause() function, maybe with a for loop or something similar.

Weitere Antworten (1)

DUY Nguyen
DUY Nguyen am 2 Mär. 2023
Hi Hayden,
Hope this code below could help you!
for i = 1:10
if (i==1)
fprintf('Man, I am getting older and wiser by the second\n');
fprintf('and now I am 1 second older\n', i);
else
fprintf('and now I am %d seconds older\n', i);
end
pause(1);
end
fprintf('and Prof. Koz just wasted approximately %d seconds of my life\n', i);

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!

Translated by