MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Nested functions are completely contained within another function. The primary
difference between nested functions and local functions is that nested functions can use
variables defined in parent functions without explicitly passing those variables as
arguments.


Nested functions are useful when subroutines share data, such as applications that pass
data between components. For example, create a function that allows you to set a value
between 0 and 1 using either a slider or an editable text box. If you use nested functions
for the callbacks, the slider and text box can share the value and each other’s handles
without explicitly passing them:


function myslider
value = 0;
f = figure;
s = uicontrol(f,'Style','slider','Callback',@slider);
e = uicontrol(f,'Style','edit','Callback',@edittext,...
'Position',[100,20,100,20]);


function slider(obj,~)
value = obj.Value;
e.String = num2str(value);
end
function edittext(obj,~)
value = str2double(obj.String);
s.Value = value;
end


end


Private Functions in a Subfolder


Like local or nested functions, private functions are accessible only to functions in a
specific location. However, private functions are not in the same file as the functions that
can call them. Instead, they are in a subfolder named private. Private functions are
available only to functions in the folder immediately above the private folder. Use
private functions to separate code into different files, or to share code between multiple,
related functions.


Anonymous Functions Without a File


Anonymous functions allow you to define a function without creating a program file, as
long as the function consists of a single statement. A common application of anonymous


Types of Functions
Free download pdf