M-function in a M-script

29 ビュー (過去 30 日間)
Fangjun Jiang
Fangjun Jiang 2011 年 5 月 18 日
回答済み: Bart 2016 年 12 月 19 日
When I write M-scripts (It's a script, not an M-Function), sometimes I want to have a quick and dirty function, such as:
test1.m
a=1;
b=MyFunction(a)
Function y=MyFunction(x)
y=x/2;
end
But it is not allowed because "FUNCTION keyword is invalid heare". I have to create another M-file called MyFunction.m to define MyFunction.
Why is that? What is the rational behind it?
I know I can work this way:
test2.m
function test2
a=1;
b=MyFunction(a)
end
function y=MyFunction(x)
y=x/2;
end
Although no need to specify the argument for function test2, still, I have to add the first line for function test2, add an "end" for function test2. And worst of all, no easy access to base workspace data.

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 5 月 18 日
  4 件のコメント
Walter Roberson
Walter Roberson 2015 年 7 月 26 日
Let me think: Fortran... C... C++... VBA... java 7 and earlier... Nope, none of those have functions as first class objects that can be defined almost anywhere.
Scripting is like leaving broken glass on the floor. If you know where it is and always remember to walk around it, it isn't going to be a problem.
Saying that functions with dozens of arguments are "as bad or worse" is like saying that if you provide people with pieces of metal and grindstones then that is worse than glass on the floor because some people might leave dangerous metal burrs on the things they shape.
I accidentally broke a bottle on my back walk yesterday. I swept it up, but I couldn't get at the slivers in some of the cracks, and it's pretty likely that my feet will discover a missed sliver at some point.
Sean de Wolski
Sean de Wolski 2015 年 7 月 29 日
編集済み: Sean de Wolski 2015 年 7 月 29 日

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

その他の回答 (1 件)

Bart
Bart 2016 年 12 月 19 日
I believe this is possible since version R2016b. See https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html.

カテゴリ

Help Center および File ExchangeHistorical Contests についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by