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

2 ビュー (過去 30 日間)
Marek Gradzki
Marek Gradzki 2020 年 8 月 7 日
コメント済み: Marek Gradzki 2020 年 8 月 7 日
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

採用された回答

Stephen23
Stephen23 2020 年 8 月 7 日
編集済み: Stephen23 2020 年 8 月 7 日
"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 件のコメント
Marek Gradzki
Marek Gradzki 2020 年 8 月 7 日
Ok, right, thanks! So I guess the main difference is about access to the variables defined in the main function.

サインインしてコメントする。

その他の回答 (1 件)

Sudheer Bhimireddy
Sudheer Bhimireddy 2020 年 8 月 7 日
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 件のコメント
Bruno Luong
Bruno Luong 2020 年 8 月 7 日
編集済み: Bruno Luong 2020 年 8 月 7 日
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
Marek Gradzki
Marek Gradzki 2020 年 8 月 7 日
Ok, thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by