How to make derived constants persistent in global constants scripts
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Akana Juliet
el 28 de Jun. de 2021
Comentada: Walter Roberson
el 28 de Jun. de 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!
0 comentarios
Respuesta aceptada
Walter Roberson
el 28 de Jun. de 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.
The "official" way to handle all of this is to use a classdef with a dependent property https://www.mathworks.com/help/matlab/matlab_oop/access-methods-for-dependent-properties.html but see also the good question at https://www.mathworks.com/matlabcentral/answers/128905-how-to-efficiently-use-dependent-properties-if-dependence-is-computational-costly
2 comentarios
Walter Roberson
el 28 de Jun. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!