How safe are nested function handles?
조회 수: 1 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Jan
2011년 8월 17일
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개)
Daniel Shub
2011년 8월 17일
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!