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

MATLABnested functionsprogrammingsubfunction

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 ?

Best Answer

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.