For statement - print on exactly 1 second
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (2)
Image Analyst
am 11 Feb. 2017
0 Stimmen
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 Kommentar
Image Analyst
am 11 Feb. 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
am 11 Feb. 2017
Bearbeitet: Dejan Hrovatin
am 11 Feb. 2017
0 Stimmen
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!