Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Disclaimer: code not tested...</p> <p>The function handle operator allows you to create a reference to a function and pass it around just like any other variable:</p> <pre><code>% function to add two numbers function total = add(first, second) total = first + second; end % this variable now points to the add function operation = @add; </code></pre> <p>Once you've got a function handle, you can invoke it just like a regular function:</p> <pre><code>operation(10, 20); % returns 30 </code></pre> <p>One nice thing about function handles is that you can pass them around just like any other data, so you can write functions that act on other functions. This often allows you to easily separate out business logic:</p> <pre><code>% prints hello function sayHello disp('hello world!'); end % does something five times function doFiveTimes(thingToDo) for idx = 1 : 5 thingToDo(); end end % now I can say hello five times easily: doFiveTimes(@sayHello); % if there's something else I want to do five times, I don't have to write % the five times logic again, only the operation itself: function sayCheese disp('Cheese'); end doFiveTimes(@sayCheese); % I don't even need to explicitly declare a function - this is an % anonymous function: doFiveTimes(@() disp('do something else')); </code></pre> <p>The <a href="http://www.mathworks.com/help/techdoc/ref/function_handle.html" rel="noreferrer">Matlab documentation</a> has a fuller description of the Matlab syntax, and describes some other uses for function handles like graphics callbacks.</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