How safe are nested function handles?
Show older comments
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?
Accepted Answer
More Answers (1)
Daniel Shub
on 17 Aug 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 Comment
John Tillinghast
on 17 Aug 2011
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!