Placing nested function in another .m-file.

18 views (last 30 days)
David on 28 Jan 2014
Commented: Walter Roberson on 21 Feb 2020
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

Answers (3)

Walter Roberson
Walter Roberson on 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().

Bardo on 19 Feb 2020
Edited: Bardo on 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
  1 Comment
Walter Roberson
Walter Roberson on 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
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
In such a case, the assignment of the function handle to sum inside mess_me_up will be recognized.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!