Subtract 1 from variable each second

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?

 Akzeptierte Antwort

Jan
Jan am 10 Jun. 2021

0 Stimmen

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 Kommentare

Mathieu NOE
Mathieu NOE am 10 Jun. 2021
Whow
I'm impressed !
so much science for a counter !
Martin
Martin am 10 Jun. 2021
me2, thanks!
Jan
Jan am 10 Jun. 2021
@Mathieu NOE: And it even counts backwards from 100 for 3 weeks. :-)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Mathieu NOE
Mathieu NOE am 10 Jun. 2021

0 Stimmen

hi
nothing fancy
counter = 100;
while true
do_something=true;
counter = counter -1; % decrement counter
pause(1); % 1 second pause
disp(counter);
end

3 Kommentare

Martin
Martin am 10 Jun. 2021
Bearbeitet: Martin am 10 Jun. 2021
yeah I know this one, but the hing is pause has to be pause(rand); (this loop can take between something like 0.001sec and 3 weeks)...
Mathieu NOE
Mathieu NOE am 10 Jun. 2021
so how do you plan to get the counter decremented every second ??
Martin
Martin am 10 Jun. 2021
Bearbeitet: Martin am 10 Jun. 2021
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2020b

Gefragt:

am 10 Jun. 2021

Kommentiert:

Jan
am 10 Jun. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by