For statement - print on exactly 1 second
Mostrar comentarios más antiguos
Hi!
I want to print some text (ex. test) 20 times, every 1 second. I tried with for statement:
close all;
clear all;
tic
for i=1:20
toc
disp('test');
pause(i-toc);
end
If I run this code, I see that time drifts also for 20 ms from whole second (I know that It depends on many things, occupancy of CPU is for ex. one thing). Is any other option to come closer to the whole second?
Thank you! Best regards, Dejan
Respuesta aceptada
Más respuestas (2)
Image Analyst
el 11 de Feb. de 2017
0 votos
Instead of pause(i-toc), use pause(1). Your way did not pause exactly 1 second every time - the time changed upon each iteration.
1 comentario
Image Analyst
el 11 de Feb. de 2017
If the time to complete each iteration changes, then you can use while and toc:
for i = 1 : 20
startTime = tic;
% Lengthy and variable code...
% Wait until 1 second has passed
elapsedTime = toc(startTime); % In seconds
while elapsedTime < 1
elapsedTime = toc(startTime); % In seconds
end
end
Dejan Hrovatin
el 11 de Feb. de 2017
Editada: Dejan Hrovatin
el 11 de Feb. de 2017
0 votos
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!