How safe are nested function handles?
Mostrar comentarios más antiguos
I would like to be able to use some code to return function handles. The easiest way to do it would use nested function handles, much like this (except doing real stuff):
function silly_fn_obj = NestedFnObjs()
function y = fn1(x);
y = 2 * x;
end
function y = fn2(x);
y = 2 * fn1(x);
end
function y = fn3(x);
y = 2 * fn2(x);
end
silly_fn_obj = @fn3;
end
And then I want to make a function handle
fh = NestedFnObjs();
The output fh should equal @fn3, which depends on the other two functions...which only exist inside NestedFnObjs.
Which will no longer be running then fh gets used.
This actually seems to work, but I don't really trust it. Should I? When does this kind of arrangement break down? How can I make sure it doesn't?
Respuesta aceptada
Más respuestas (1)
Daniel Shub
el 17 de Ag. de 2011
In general you can trust MATLAB handle objects to do what they are supposed to and if you construct them correctly, they will even do what you want. I would suggest the same level of concern for function handles and graphics handles (basically none).
While your function NestedFnObjs is "no longer running" parts of it are effectively still in memory since fh points to @fn3. Consider:
x = rand(1e7, 2);
fh = @(i)(x(i));
[x(2), fh(2)]
clear x
fh(2)
1 comentario
John Tillinghast
el 17 de Ag. de 2011
Categorías
Más información sobre Loops and Conditional Statements 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!