MATLAB Answers

Placing nested function in another .m-file.

조회 수: 42(최근 30일)
David
David 28 Jan 2014
댓글: Walter Roberson 21 Feb 2020
Hi,
is it possible to place nested function in another .m-file through e.g. function handles? Lets say that I want to keep the benefits of the nested function with shared workspace, but there is alot of code in the nested function itself and for clarity reason I want to put it in another file - is this possible? Example
function p = f1() x = 1; function doStruff() x = x + 1; end end
replaced by
f1 = @function_handle or anotherMfile('callback', x) function p = f1() x = 1; x = anotherMfile(x); end

  댓글 수: 0

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

답변(3개)

Thomas
Thomas 28 Jan 2014

  댓글 수: 1

David
David 28 Jan 2014
I don't an example on where the nested function is placed within another .m-file though. Could you provide such?

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


Walter Roberson
Walter Roberson 8 Feb 2014
No, nested functions must be defined within another function in the same file. A function in another file does not have unrestricted access to the variables in the outer function(s).
You can create setter and getter functions that have access to the necessary variables and then export the file handles to be used in routines in other files, but that does not give you much (if any) flexibility compared to not nesting but exporting a handle to an anonymous function that uses subsref() or subsassgn().

  댓글 수: 0

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


Bardo
Bardo 19 Feb 2020
편집: Bardo 20 Feb 2020
> for clarity reason I want to put it in another file - is this possible?
In C or other languages one would use a #include statements.
In Matlab, put your code in separate files other1.m, other2.m - as scripts, not as functions.
(which BTW was the only way in the beginnings of Matlab)
then call them
bla
bla
other1;
bla
other2;

  댓글 수: 1

Walter Roberson
Walter Roberson 21 Feb 2020
Note that Mathworks has been getting stricter and stricter about the effects of accessing variables or functions assigned to in scripts, if the name was not assigned to in clear ways before the function was called.
For example if you have a function like
function test
mess_me_up
sum(1:10)
end
together with script mess_me_up.m
sum = @(x) x.^2;
then in the old model that scripts were just like executing the code in place (same as C/C++ #include) then the result should be a list of the squares of the integers 1 to 10, because the sum assigned to inside mess_me_up should override the normal sum() function. However, in recent versions of MATLAB, the optimizer will refuse to recognize that sum was assigned to inside mess_me_up and will use the standard function named sum() when executing sum(1:10), unless sum was assigned to before the script is called, such as
function test
sum = []; %any assignment will do
mess_me_up
sum(1:10)
end
In such a case, the assignment of the function handle to sum inside mess_me_up will be recognized.

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


Translated by