For statement - print on exactly 1 second
Show older comments
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
Accepted Answer
More Answers (2)
Image Analyst
on 11 Feb 2017
0 votes
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 Comment
Image Analyst
on 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
on 11 Feb 2017
Edited: Dejan Hrovatin
on 11 Feb 2017
0 votes
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!