how to make a variable execute only once ?

31 views (last 30 days)
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 Comments
Reema Alhassan
Reema Alhassan on 12 Jun 2018
I need to make a string every time I run the code for example the first time Reema0 then Reema1 then Reema2 and so on and yes I'm using a script

Sign in to comment.

Accepted Answer

Jan
Jan on 12 Jun 2018
Edited: Jan on 12 Jun 2018
If you need a persistent variable, it is required to store the code in a function. To be exact, at least the persistent variable must be contained in a function:
function C = YourCounter
persistent CP
if isempty(CP)
CP = 0;
end
CP = CP + 1;
C = CP;
end
Now the counter is increased with each call:
str = sprintf('Hello %d', YourCounter)
str = sprintf('Hello %d', YourCounter)
str = sprintf('Hello %d', YourCounter)
You can reset it by:
clear YourCounter
I suggest to write the complete code as a function, because polluting the workspaces is prone to bugs and hard to maintain.
Note: As soon as you have a brute clear all anywhere in your code, the persistent variable is killed also. So stay away from clear all.

More Answers (1)

OCDER
OCDER on 12 Jun 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

Community Treasure Hunt

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

Start Hunting!