How to make derived constants persistent in global constants scripts

2 ビュー (過去 30 日間)
Akana Juliet
Akana Juliet 2021 年 6 月 28 日
コメント済み: Walter Roberson 2021 年 6 月 28 日
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 件のコメント
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 件)

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by