how to make a variable execute only once ?
Mostra commenti meno recenti
Hello I have a viable t I want it to be 0 only for once then I need to increment it by 1 each time when I do this
t=0;
t=t+1;
it is always = 1 ; I have also used "persistent" but I got an error "The PERSISTENT declaration must be in a function " does anyone knows how to do this ?
thank you
2 Commenti
Geoff Hayes
il 12 Giu 2018
Reema - you may need to post more of your code. Or provide some context around why you want this variable to be zero some of the time but set to one at other times. Is this meant to be some kind of boolean? Given the persistent error message, I think that you are using a script (or running some code from the command line) and so you may want to use a function instead.
Reema Alhassan
il 12 Giu 2018
Risposta accettata
Più risposte (1)
OCDER
il 12 Giu 2018
Or you could make a class of type handle that stores the value of t. Every time you summon the method getStr, it'll return the "ReemaN" string AND THEN update N by 1.
%Save the following code as: MakeName.m
classdef MakeName < handle
properties (Access = public)
t = 0;
end
methods
function incr(obj)
obj.t = obj.t + 1;
end
function decr(obj)
obj.t = obj.t - 1;
end
function reset(obj)
obj.t = 0;
end
function S = getStr(obj)
S = sprintf('Reema%d', obj.t);
incr(obj);
end
end
end
To see how to use this object called MakeName, try the following:
A = MakeName;
A.getStr %Reema0
A.getStr %Reema1
A.getStr %Reema2
A.reset %reset value of t to 0. Same as A.t = 0;
A.getStr %Reema0
A.t = 10; %set value of t to 10.
A.getStr %Reema10
Categorie
Scopri di più su Creating, Deleting, and Querying Graphics Objects in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!