Make memoized function calls recognize equivalent input sequences (and so avoid redundant cache entries)
Mostrar comentarios más antiguos
In the demo below, we see that the memoized function func() executes twice out of the three times it is called. Ideally, it would only execute upon the first call, but the memoization engine fails to recognize that (1) and (2) are equivalent calls. Is there any way to get a memoized function to ignore differences in the ordering of Name/Value arguments?
mf=memoize(@func);
mf('A',1,'B',2) %(1) Cached
mf('B',2,'A',1) %(2) Cached
mf('A',1,'B',2) %(3) Not Cached
function func(opts)
arguments
opts.A
opts.B
end
disp("Executing")
end
2 comentarios
As you've written them (1) and (2) are equivalent, but that's not necessarily true in general. The ordering of the name-value arguments can matter, particularly in the case where one or more names are repeated.
f1 = figure(Color = "r", Color = "g");
f1.Color % Green figure
f2 = figure(Color = "g", Color = "r");
f2.Color % Red figure
No, this behavior is not a bug. It can be useful in a case where you want to fix a particular name-value argument in a function you're writing but allow users to override that by specifying the same argument when they call your function.
createFigure = @(varargin) figure("Color", "r", varargin{:});
If I call createFigure with no inputs, it makes a red figure.
f3 = createFigure();
f3.Color % Red figure by default
But I (or a user of my createFigure function) can override this. They don't need to know or care which arguments I used to call the figure constructor.
f4 = createFigure(Color = "g");
f4.Color % Green figure
Memoization treating the lines of code that define f1 and f2 as the same would be incorrect.
I used an object constructor above, but specifying a repeated name-value argument works the same way with a regular function.
func(A = 1, B = 2, A = 3)
I believe objects can make this type of scenario more likely to happen, particularly if you have Dependent properties or properties that interact with one another like some of the "Mode" properties of some of the graphics objects (explicitly setting the XLim property of an axes changes the XLimMode property of that axes from 'auto' to 'manual', for example.) The Units and Position properties of Handle Graphics objects also interact and can depend on the order in which they're specified.
function func(opts)
arguments
opts.A
opts.B
end
disp("Executing")
disp(opts)
end
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!