How to make derived constants persistent in global constants scripts

2 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

Walter Roberson
Walter Roberson le 28 Juin 2021
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 commentaires
Akana Juliet
Akana Juliet le 28 Juin 2021
@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 le 28 Juin 2021
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by