Filter löschen
Filter löschen

If in one .m file, I write a nested function inside the main function, then I wonder if this nested function can call a function in another .m file?

2 Ansichten (letzte 30 Tage)
I know that local functions cannot call exterior functions (i.e., functions in other .m files) but the main function can, however, what about the nested function?

Antworten (1)

Walter Roberson
Walter Roberson am 19 Feb. 2016
Local functions and nested functions can call any reachable function, whether in the same .m or a different .m
The restriction is "reachable". Usually a local or nested function can only reach functions that are in the same .m or which are the first function in a .m file. However, if the local or nested function has access to a function handle to a buried function, then it can execute the function.
For example:
file file1.m
function file1
f1 = file2();
function nested1
f1(7);
end
nested1()
end
file file2.m
function h = file2
h = @local2;
function y = local2(x)
y = x.^2 - 1;
Here, calling upon file2 returns a handle to the local function local2. Once that handle has been stored in f1, nested1 can use that handle to invoke local2 even though local2 would otherwise not be reachable from nested1 (because it is not the first function in its own .m file)

Kategorien

Mehr zu Workspace Variables and MAT-Files finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by