필터 지우기
필터 지우기

how to intialize a variable only once?the below written code should execute only once.later the value must b retained. how it is done

조회 수: 16 (최근 30일)
example
persistent a
if isempty (a)
a=0;
end
  댓글 수: 2
Stephen23
Stephen23 2015년 3월 1일
편집: Stephen23 2015년 3월 1일
That should work.
What is the problem? Is this code is placed at the beginning of a function (and not a script )? Did you try it? What happens that you don't expect?
If you want to share this variable between functions, then you should pass it as an input/output variable (and avoid using globals).
rashmi am
rashmi am 2015년 3월 1일
yes,it is working.but what i needed is once i close the m-file containing this variable and then run it again, 'a' shouldn't be set to 0 .i want previously computed values as such for further computation.

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

채택된 답변

Image Analyst
Image Analyst 2015년 3월 1일
You say "the value assigned to 'a' in the previous computation should be retained, after I close the m-file and run it next time." So, save it to a .mat file on disk with save() then. Recall it with load() the next time you run the program.
persistent a
if isempty (a)
a=0;
if exist('a.mat', 'file')
% Recall a from mat file
s = load('a.mat');
a = s.a;
end
end
% more code....
% Then just before you exit this routine, save it out to the disk file
% for recall by later runs of this program.
save('a.mat', a);
Of course since you're saving it and recalling it across different runs, it no longer needs to be persistent. You could just do load() and save() and not have it be persistent.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 3월 1일
That code looks fine in itself. See here for the examples in the documentation for persistent. persistent variables, like global variables, are initialized to [], so testing them for that value, just as you did, is correct for determining whether they have been initialized.
Note that persistent variables are only visible inside the routine they are declared in, so they are not the correct choice for creating a shared variable.
  댓글 수: 1
rashmi am
rashmi am 2015년 3월 1일
yes,it works.But the value assigned to 'a' in the previous computation should be retained ,after i close the m-file and run it next time.

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

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by