Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <a href="https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html" rel="nofollow noreferrer">function handle operator</a> in MATLAB acts essentially like a pointer to a specific instance of a function. Some of the other answers have discussed a few of its uses, but I'll add another use here that I often have for it: maintaining access to functions that are no longer "in scope".</p> <p>For example, the following function initializes a value <code>count</code>, and then returns a function handle to a nested function <code>increment</code>:</p> <pre><code>function fHandle = start_counting(count) disp(count); fHandle = @increment; function increment count = count+1; disp(count); end end </code></pre> <p>Since the function <code>increment</code> is a <a href="https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html" rel="nofollow noreferrer">nested function</a>, it can only be used within the function <code>start_counting</code> (i.e. the workspace of <code>start_counting</code> is its "scope"). However, by returning a handle to the function <code>increment</code>, I can still use it outside of <code>start_counting</code>, and it still retains access to the variables in the workspace of <code>start_counting</code>! That allows me to do this:</p> <pre><code>&gt;&gt; fh = start_counting(3); % Initialize count to 3 and return handle 3 &gt;&gt; fh(); % Invoke increment function using its handle 4 &gt;&gt; fh(); 5 </code></pre> <p>Notice how we can keep incrementing count even though we are outside of the function <code>start_counting</code>. But you can do something even more interesting by calling <code>start_counting</code> again with a different number and storing the function handle in another variable:</p> <pre><code>&gt;&gt; fh2 = start_counting(-4); -4 &gt;&gt; fh2(); -3 &gt;&gt; fh2(); -2 &gt;&gt; fh(); % Invoke the first handle to increment 6 &gt;&gt; fh2(); % Invoke the second handle to increment -1 </code></pre> <p>Notice that these two different counters operate independently. The function handles <code>fh</code> and <code>fh2</code> point to different instances of the function <code>increment</code> with different workspaces containing unique values for <code>count</code>.</p> <p>In addition to the above, using function handles in conjunction with nested functions can also help streamline GUI design, as I illustrate in <a href="https://stackoverflow.com/a/425347/52738">this other SO post</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload