How to use a timer to increase the value of a variable?

조회 수: 7 (최근 30일)
monmatlab
monmatlab 2017년 1월 5일
답변: Adam 2017년 1월 5일
I want to increase the value of handles.i by one after each iteration but this should happen after a certain amount of time. Using pause is not possible, as if would stop another function.
I tried to do it this way
t = timer('TimerFcn',@(x,y)(handles.i=handles.i+1),'StartDelay',1);
start(t)
this is not accepted as a valid expression, so I thought it would solve the problem if created a function
function increase()
handles.i=handles.i+1
and then use the timer this way:
t = timer('TimerFcn',@(x,y) increase(), 'StartDelay',1);
I get the error that handles is unknown, but I am not sure why. Is there another way to preform this task?

채택된 답변

Adam
Adam 2017년 1월 5일
You would need to create the function as a nested function though in GUIDE this is problematic because functions are not terminated by an 'end' command so you cannot nest functions unless you manually add an 'end' to all GUIDE-created functions and do this for every new function added.
handles being unknown is easy to solve by just passing it into your function, but this would not solve your problem as it would also need to be passed out of the function to be of use. You could probably instead pass in the handle of your GUI (which you should always do in callbacks rather than passing handles directly anyway) and then retrieve handles from this and rewrite them to it - e.g.
function increase( hGUI )
handles = guidata( hGUI )
handles.i=handles.i+1
guidata( hGUI, handles )
and call
t = timer('TimerFcn',@(x,y) increase( handles.figure1 ), 'StartDelay',1);
That is using the default tag for your main figure if you haven't changed it. I always change mine because 'figure1' is not a sensible tag for every GUI I ever want to write!
The other option to get around needing an output argument is to wrap your counter variable in a handle-derived class and pass this to the timer function.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by