Why does Timer callback experience "too many output arguments" errors?
이전 댓글 표시
I am working on a Matlab Application which has a constantly running timer created in its StartupFcn:
% Build a new timer
app.refreshTimer = timer( ...
'Name', 'MATLAPP_RefreshTimer', ...
'Period', 0.1, ...
'ExecutionMode', 'fixedSpacing', ...
'TasksToExecute', Inf, ...
'TimerFcn', app.refreshTick());
% And start it
start(app.refreshTimer);
The function refreshTick() is actually empty and is a public method in the app.
methods (Access = public)
function refreshTick(app)
% Do nothing
disp(app.FUELPressButton.Value)
return
end
end
When the timer expires, I see the following error:
Error using gith/refreshTick
Too many output arguments.
Error in gith/startupFcn (line 93)
'TimerFcn', app.refreshTick());
Error in gith (line 594)
runStartupFcn(app, @startupFcn)
But the function has no output... why does this happen?
I can sidestep the issue by making the function anonymous:
% Build a new timer
app.refreshTimer = timer( ...
'Name', 'MATLAPP_RefreshTimer', ...
'Period', 0.1, ...
'ExecutionMode', 'fixedSpacing', ...
'TasksToExecute', Inf, ...
'TimerFcn', @(~,~)app.refreshTick());
% And start it
start(app.refreshTimer);
But I do not really understand why that works. I would love a solid technical explanation of what's happening here to cause this, if anyone understands this interaction.
채택된 답변
추가 답변 (1개)
Voss
2022년 4월 3일
Specifying the TimerFcn like this:
'TimerFcn', app.refreshTick(), ...
actually calls the function app.refreshTick, and then tries to set the TimerFcn to the result returned from calling app.refreshTick, but there is no result so you get the error. (Note that the error message says the error happens in startupFcn itself.)
Instead, specify it like this:
'TimerFcn', app.refreshTick, ...
because that refers to the function without calling it. The () on the end calls the function with no inputs.
댓글 수: 2
Walter Roberson
2022년 4월 3일
'TimerFcn', @app.refreshTick, ...
would refer to the function without calling it.
However the function would be called with two parameters. If the function is defined not to accept any parameters then @(~,~)app.refreshTick() or @(varargin) app.refreshTick() is appropriate
"Instead, specify it like this:'TimerFcn', app.refreshTick, because that refers to the function without calling it."
Are you sure about that (incorrect) statement?
" The () on the end calls the function with no inputs."
And what happens when there are no parentheses...?
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!