passing variable to function called by timer function

조회 수: 1 (최근 30일)
Jack
Jack 2012년 12월 13일
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
Jan
Jan 2012년 12월 13일
편집: Jan 2012년 12월 13일
Who has closed this thread and why? Because I do not see a reason, I re-open it now.
@Jack: You can re-open a thread also just by editing the question.
[EDITED]: Whoops?! You have closed this thread by your own? I assume, this was a mistake.
Jan
Jan 2012년 12월 13일
편집: Jan 2012년 12월 13일
Please learn how to format code in this forum nicely. This topic is discussed several times each day, so I assume you can find the instructions by yourself. Thanks.

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
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.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by