how to make a variable execute only once ?
显示 更早的评论
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 个评论
Geoff Hayes
2018-6-12
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
2018-6-12
采纳的回答
更多回答(1 个)
OCDER
2018-6-12
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
类别
在 帮助中心 和 File Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!