# How to make derived constants persistent in global constants scripts

1 view (last 30 days)
Akana Juliet on 28 Jun 2021
Commented: Walter Roberson on 28 Jun 2021
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 on 28 Jun 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.
Akana Juliet on 28 Jun 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 on 28 Jun 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.

### Categories

Find more on Annotations in Help Center and File Exchange

R2019a

### Community Treasure Hunt

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

Start Hunting!