how to make a variable execute only once ?

조회 수: 57 (최근 30일)
Reema Alhassan
Reema Alhassan 2018년 6월 12일
답변: OCDER 2018년 6월 12일
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
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
Reema Alhassan 2018년 6월 12일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2018년 6월 12일
편집: Jan 2018년 6월 12일
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.

추가 답변 (1개)

OCDER
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

카테고리

Help CenterFile Exchange에서 Manage Design Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by