how to make a variable execute only once ?
12 ビュー (過去 30 日間)
古いコメントを表示
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.
採用された回答
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
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
0 件のコメント
参考
カテゴリ
Help Center および 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!