How safe are nested function handles?

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?

 採用された回答

Jan
Jan 2011 年 8 月 17 日

0 投票

If your example is working, it is safe also. MATLAB's memory manager is very trustworthy: If a function handle gets invalid, it cannot be used by accident as e.g. in C.
The method breaks down, if you modify the M-file programmatically while MATLAB is running. Then you'd need "clear < filename >" to reload the file, and this kills the function handle also.
Do you have a reason to use nested functions? In your example sub-functions are sufficient also.

1 件のコメント

John Tillinghast
John Tillinghast 2011 年 8 月 17 日
I'm writing code to make function handles that are passed to some existing code (written by a different group--I don't want to mess with the existing stuff).

サインインしてコメントする。

その他の回答 (1 件)

Daniel Shub
Daniel Shub 2011 年 8 月 17 日

0 投票

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 件のコメント

John Tillinghast
John Tillinghast 2011 年 8 月 17 日
Thank you. I'm still pleasantly surprised that this seems to work all right. I am used to computers being fussy about such things.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by