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?
댓글 수: 0
채택된 답변
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
댓글 수: 3
추가 답변 (1개)
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!