Subtract 1 from variable each second

2 次查看(过去 30 天)
Imagine I got something like this:
counter = 100;
while true
do_something=true;
pause(rand);
disp(counter);
end
Then I need the counter variable to get subtracted by 1 each second inside the while loop. Any suggestions?

采纳的回答

Jan
Jan 2021-6-10
counter = 100;
TimerH = timer('TimerFcn', @doCount, 'ExecutionMode', 'fixedRate', ...
'Period', 1.0, 'UserData', counter);
start(TimerH);
while true
do_something=true;
pause(rand);
counter = TimerH.UserData;
disp(counter);
end
delete(TimerH);
function doCount(TimerH, EventData)
TimerH.UserData = TimerH.UserData - 1;
end
Do you really need an active counter?
iniTime = clock;
while true
do_something=true;
pause(rand);
counter = 100 - etime(clock, iniTime);
disp(counter);
end

更多回答(1 个)

Mathieu NOE
Mathieu NOE 2021-6-10
hi
nothing fancy
counter = 100;
while true
do_something=true;
counter = counter -1; % decrement counter
pause(1); % 1 second pause
disp(counter);
end
  3 个评论
Mathieu NOE
Mathieu NOE 2021-6-10
so how do you plan to get the counter decremented every second ??
Martin
Martin 2021-6-10
编辑:Martin 2021-6-10
yeah thats my question :) I guess I need to use
now
(before the loop) and also indside the loop, but I have hard times figure it out which is why I am asking

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by