loop problem with time delay

조회 수: 3 (최근 30일)
Hayden O'Neil
Hayden O'Neil 2017년 10월 5일
답변: DUY Nguyen 2023년 3월 2일
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.

채택된 답변

James Tursa
James Tursa 2017년 10월 6일
편집: James Tursa 2017년 10월 6일
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.

추가 답변 (1개)

DUY Nguyen
DUY Nguyen 2023년 3월 2일
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);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by