필터 지우기
필터 지우기

Two ways of M-subfunction definition: what are discrepances?

조회 수: 1 (최근 30일)
Igor
Igor 2011년 5월 18일
As known, there are 2 ways -- nested subroutines and secondaries subr.
1. nested
function...
...
function...
...
end
...
end
2. primary/secondary
function
...
end
function
...
end
From header (primary function)one can call both nested and secondary subfunctions.
But what kind is better to use? What are differences between ?

채택된 답변

Andrew Newell
Andrew Newell 2011년 5월 18일
The primary/secondary functions are much like two functions in separate files, except that the secondary functions (called subfunctions) are only seen by the other functions in the same file. Generally, the variables in functions should be hidden from each other, so this is the default choice. Use nested functions when you need the specific advantages that stem from having access to variables in the workspace of the calling function.
Nested functions are great for:
  1. "Memoizing" (storing) results of costly calculations for later use (see Loren's blog).
  2. Creating custom functions with hidden parameters that are set by the calling function (as in this example). This is like a fancy anonymous function.
  댓글 수: 1
Matt Fig
Matt Fig 2011년 5월 18일
I would add
3. GUI callbacks. The use of nested functions for GUIs eliminates almost all "How do I share data between callbacks" questions. When I write a complex GUI, it is only with nested functions anymore.

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

추가 답변 (2개)

Yoav Livneh
Yoav Livneh 2011년 5월 18일
In the first case, the second function is nested and only the outer function can call it. Furthermore the nested function can read and use parameters from the caller function's workspace.
In the second case each function has its own workspace and they don't share parameters.

Igor
Igor 2011년 5월 18일
Thanks for answers. As I understand, if varname in nested func. coincides with varname in primary func. that uses variable that was defined in primary func. Perhaps, secondary func. is like private methods in object oriented programming.
Another question, on analogy with C++. When I call nested or secondary func. -- subfun(par) -- a new region of memory is reserved and here value is copied from calling func. That is -- dublicating exists.
  댓글 수: 2
Andrew Newell
Andrew Newell 2011년 5월 18일
Yes, subfunctions are a bit like private methods.
No, the value of a function argument is not copied unless the argument is changed within the function. See http://www.mathworks.com/help/techdoc/matlab_prog/brh72ex-2.html#brh72ex-13.
Igor
Igor 2011년 5월 18일
On 2nd question: but if changed then copied!
Very rational rule!

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

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by