필터 지우기
필터 지우기

How to make derived constants persistent in global constants scripts

조회 수: 1 (최근 30일)
Hi all, I am still learning the ins and outs of MATLAB and I am stuck on this part. I am trying to make derived constants persistent, and I can't seem to get it to work. If I had constants like: x = 1 and y = 2, and then xy = x + y, how would I make xy persistent? This is a simplified example but generally the issue I am having right now is that I don't have the correct syntax or a proper understanding. It would be okay if I need to make a separate function file, whatever works best to make multiple derived constants persistent!
Thank you so much in advance!

채택된 답변

Walter Roberson
Walter Roberson 2021년 6월 28일
You asked about this the other day, and you included proposed implementation code using persistent and isempty . That proposed code was functional. I would, however, suggest an implementation function closer to
function dc = derived_constants(x, y)
persistent xy
if nargin < 2
if isempty(xy)
error('must initialize the derived constants');
end
dc = xy;
else
xy = x + y;
dc = xy;
end
end
as compared to your implementation, which went something like
function dc = derived_constants(x, y)
persistent xy
if isempty(xy)
xy = x + y;
end
dc = xy;
end
The difference is that my version permits you to reinitialize the output, and my version can be called with no arguments once it is initialized.
  댓글 수: 2
Akana Juliet
Akana Juliet 2021년 6월 28일
@Walter Roberson Thank you so much for your response! And I'm seriously impressed with your impeccable memory from last Friday! haha.
What does it mean when you say "if nargin < 2"
Walter Roberson
Walter Roberson 2021년 6월 28일
nargin is the number of parameters that were passed to the function. In some cases it makes sense to let trailing parameters be left off, and this is the way you can tell whether the user provided the values
So you would call it once passing in x and y values and it would remember. But after that you could call with no parameters.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by