Is it possible to call a subfunction inside a function mscript?

Is it possible to call a subfunction inside a mscript function and get the returned value?
e.g., the content of 'func.m' as below
function b = func(a)
b = subfunc(a) +1;
function c = subfunc(a)
c = a*2;
Can I call subfunc directly in the matlab workspace.

댓글 수: 3

Stephen23
Stephen23 2015년 2월 16일
편집: Stephen23 2015년 2월 16일
What do you mean by "subfunction" ? Do you mean a "local function" , or something else?
For instance, a function Func is stored in file 'Func.m'. In 'Func.m', there is a function SubFunc called by the main Func function. I wanna if I can excute the SubFunc function in 'Func.m' directly.
Stephen23
Stephen23 2015년 2월 18일
편집: Stephen23 2018년 2월 17일
MATLAB does not mention "subfunctions". Other functions in the same Mfile are either local functions or nested functions.
Do not call any function a "script", as a script is something quite different from a function.
"I wanna if I can excute the SubFunc function in 'Func.m' directly": lets look at the two possible cases for this:
  • If Func is the main function on that Mfile, then it can call any local function in the same Mfile.
  • If Func is a script then from version R2016b you can add local functions. With earlier versions doing so will throw an error.

댓글을 달려면 로그인하십시오.

 채택된 답변

Thorsten
Thorsten 2015년 2월 16일

1 개 추천

No. You have to create a separate mfile that can be called by your mscript.

추가 답변 (2개)

Jan
Jan 2017년 1월 25일
You can do this by a wrapper:
function Fcn = main
Fcn.func = @func;
Fcn.subfunc = @subfunc;
function b = func(a)
b = subfunc(a) +1;
function c = subfunc(a)
c = a*2;
Now you can call from the outside:
Fcn = main();
Fcn.func(1)
Fcn.subfunc(2)
Adam
Adam 2015년 2월 16일
편집: Adam 2015년 2월 18일

1 개 추천

You can call a sub-function from a main function in an m-file.
You cannot call a sub-function from a script (what would the function be 'sub' of?!). If you need to then just turn your script into a function.
Edit: In response to your edited question, then Yes, what you are doing is creating a function file and then within it defining subfunctions which are only accessible to the main function of that file.
This does seem like a question that you could have got the answer to yourself instantly though by simply putting that code in a file and running it!

댓글 수: 1

Of course I know it is impossible to call the local function by excuting subfunc() from outside.
I'm asking if there is a way to call a local function from outside.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

질문:

2015년 2월 16일

편집:

2018년 2월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by