Filter löschen
Filter löschen

how to define a variable used one time in function

3 Ansichten (letzte 30 Tage)
Maria
Maria am 14 Mär. 2014
Beantwortet: Walter Roberson am 14 Mär. 2014
if i have a function with a variable x=1 defined in side that function and the variable is increased by a formula and that function is called many times from another function , the question is how can make that variable x defined in side the function is set only at the first call and after the other calls it will not effect or set to 1 again , or in another meaning how to define a variable used one time in function , please do not tell me to define x=1 out of function body because the program that i worked on not allowed .
for example :
Function ABC()
x=1;
x=x+Pi;
end

Antworten (2)

Mischa Kim
Mischa Kim am 14 Mär. 2014
Bearbeitet: Mischa Kim am 14 Mär. 2014
ALAA, you can define x to be a global variable. Alternatively, you could use
function xnew = ABC(x)
...
xnew = x + Pi;
end
to return the new value of x to the calling function.
  1 Kommentar
Maria
Maria am 14 Mär. 2014
Bearbeitet: Maria am 14 Mär. 2014
Dear Mischa Many thanks
actually the main function had not called from any other function , actually I am working on simulink/matlab and the function is in function block (s-function ) and that function connected with robot model so it outputs variables to the model , actually i want to make random obstacles defined inside function block but the obstacles returned to their first location after the first feedback between model and function because i defined first obstacles locations in side function then i moved them randomly by rand(), so after second call they return to first locations due to first definitions of their locations inside function , so any suggestion
Ex:
function t=ABC ()
obstacle= [2 4];
obstacle(1)=obstacle(1)+rand() * 0.02; obstacle(2)=obstacle(2)+rand() * 0.03;

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 14 Mär. 2014
persistent x
if isempty(x); x = 1; else; x = x + 1; end

Kategorien

Mehr zu Event Functions finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by