passing variable to function called by timer function

1 vue (au cours des 30 derniers jours)
Jack
Jack le 13 Déc 2012
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 commentaires
Jan
Jan le 13 Déc 2012
Modifié(e) : Jan le 13 Déc 2012
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 le 13 Déc 2012
Modifié(e) : Jan le 13 Déc 2012
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.

Connectez-vous pour commenter.

Réponses (1)

Jan
Jan le 13 Déc 2012
Modifié(e) : Jan le 13 Déc 2012
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.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by