Location of the "end" statement of the main function in a m. file?

1 Ansicht (letzte 30 Tage)
Hello,
could someone write what is the difference between possible location of the "end" statement of the main function: before first local function vs end of a file? What is the difference?
For example: first vs. second case in this answer.
Thank you!
Marek

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Aug. 2020
Bearbeitet: Stephen23 am 7 Aug. 2020
"before first local function"
any functions defined after the main function are local functions:
"vs end of a file?"
any functions defined within the main function are nested functions:
These can be combined too, e.g.:
function mymain()
... code
function mynest()
... code
end % mynest()
end % mymain()
function mylocal()
... code
end % mylocal()
Nested functions have access to the parent function's workspace. Local functions do not.
  1 Kommentar
Marek Gradzki
Marek Gradzki am 7 Aug. 2020
Ok, right, thanks! So I guess the main difference is about access to the variables defined in the main function.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sudheer Bhimireddy
Sudheer Bhimireddy am 7 Aug. 2020
If you have 'end' at the end of a file, then your functions become 'Nested functions'. The variables created inside the function and their scope changes.
Read this, this and this MATLAB documentation.
Hope this helps.
  3 Kommentare
Bruno Luong
Bruno Luong am 7 Aug. 2020
Bearbeitet: Bruno Luong am 7 Aug. 2020
function caller
a = 1;
function c = foo(d)
eval('b = d;'); % error "forbidden"
c = a + b;
end
function c = bar(d)
b = [];
eval('b = d;'); % OK
c = a + b;
end
fprintf('bar(2) = %g\n', bar(2));
fprintf('foo(2) = %g\n', foo(2)); % this won't run
end

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Variables 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