passing variable to function called by timer function
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello- I'm trying to produce a timer "count" which calls a function "test" at regualar intervals. This function then increments a variable "t" every time it is called.
So far I have simulated the function being called correctly, and printing the value of "t" in the command window, however if I try to increment the variable (t = t+1;) I get the error "The expression to the left of the equals sign is not a valid target for an assignment." (I've put this as comment in function otherwise it doesn't run when called)
Also, If I change the value of "t", and restart the timer "count" the value of t which is printed is unchanged.
======================in command window==========================
>> global t;
>> set(count,'TimerFcn',{@test t});
>> set(count,'Period',0.5);
>> start(count);
ans =
[1x0 char]
ans =
[1x0 char]
ans =
[1x0 char]
stop(count);
====================function============================
function [] = test(~,~,t)
{
%t=t+1;
sprintf('%d', t);
}
end
================================================
Can anyone point out why my code isn't producing what I'm after?
댓글 수: 2
답변 (1개)
Jan
2012년 12월 13일
편집: Jan
2012년 12월 13일
If t is declared as global already, you do not have to provide it as input argument. But if you do this, you cannot change the value. But I'm surprised, that this is an error and not only useless.
But the curly braces in your function are an error. Matlab is not C!
set(count, 'TimerFcn', @test);
...
function test(TimerH, EventData)
global t % declare as global whereever it is used
t = t+1;
sprintf('%d', t);
end
In real programs using a global variable is a bad idea. Better store t in the Userdata of the timer.
댓글 수: 0
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!