For statement - print on exactly 1 second
古いコメントを表示
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
採用された回答
その他の回答 (2 件)
Image Analyst
2017 年 2 月 11 日
0 投票
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 件のコメント
Image Analyst
2017 年 2 月 11 日
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
2017 年 2 月 11 日
編集済み: Dejan Hrovatin
2017 年 2 月 11 日
0 投票
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!