How safe are nested function handles?

조회 수: 1 (최근 30일)
John Tillinghast
John Tillinghast 2011년 8월 17일
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일
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일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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!

Translated by