Calling timer function from within another function

3 ビュー (過去 30 日間)
Giles
Giles 2011 年 6 月 29 日
I want to use the timer function within another function. Moreover, it must have access to the values of variables within that function in order for its callback commands to execute. However, the timer function always works in the base workspace, even if called from a function (which seems extremely counterintuitive, but there it is). So, how do I allow it to know about the variables within the function it's being called from? For e.g., the following function doit should display 2 every second for 5 seconds, but it won't because the timer executes in the base workspace and x is not present in that workspace. (Also, I want to avoid having to explicitly assign a copy of x in the base workspace from within the function doit, such as by using the assignin command - there should be a better way to do it than that.)
function doit
x=2;
t=timer('TimerFcn', 'x', 'ExecutionMode', 'fixedRate', 'Period', 1);
start(t)
pause(5)
stop(t)
delete(t)

回答 (3 件)

Sean de Wolski
Sean de Wolski 2011 年 6 月 29 日
doc timerfind

Paulo Silva
Paulo Silva 2011 年 6 月 29 日
function doit
x=2;
t=timer('TimerFcn', @fun, 'ExecutionMode', 'fixedRate', 'Period', 1);
function fun(obj,event)
x
end
start(t)
pause(5)
stop(t)
delete(t)
end
  2 件のコメント
Walter Roberson
Walter Roberson 2011 年 6 月 29 日
Or very nearly equivalently:
function doit
x=2;
t = timer('TimerFcn', @(obj,event) x, 'ExecutionMode', 'fixedRate', 'Period', 1);
start(t)
pause(5)
stop(t)
delete(t)
end
Paulo Silva
Paulo Silva 2011 年 6 月 29 日
Nice one Walter, I must remember that one, thanks

サインインしてコメントする。


Giles
Giles 2011 年 7 月 1 日
Thanks. So wait, just because you happen to specify the callback as a function handle (or perhaps using the cell array syntax for specifying functions and input arguments) suddenly timer runs inside the function doit (from where it is called), whereas otherwise it runs in the base workspace? Why????????? How would anybody know to do this? This is so arbitrary. Why does it not simply run where it is called? Arg.
  1 件のコメント
Paulo Silva
Paulo Silva 2011 年 7 月 1 日
Not that arbitrary, please read the documentation so you can better understand
doc function_handle

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by