Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Function handles are an extremely powerful tool in matlab. A good start is to read the online help, which will give you far more than I can. At the command prompt, type</p> <pre><code>doc function_handle </code></pre> <p>A function handle is a simple way to create a function in one line. For example, suppose I wished to numerically integrate the function sin(k*x), where k has some fixed, external value. I could use an inline function, but a function handle is much neater. Define a function</p> <pre><code>k = 2; fofx = @(x) sin(x*k); </code></pre> <p>See that I can now evaluate the function fofx at the command line. MATLAB knows what k is, so we can use fofx as a function now.</p> <pre><code>fofx(0.3) ans = 0.564642473395035 </code></pre> <p>In fact, we can pass fofx around, effectively as a variable. For example, lets call quad to do the numerical integration. I'll pick the interval [0,pi/2].</p> <pre><code>quad(fofx,0,pi/2) ans = 0.999999998199215 </code></pre> <p>As you can see, quad did the numerical integration. (By the way, an inline function would have been at least an order of magitude slower, and far less easy to work with.)</p> <pre><code>x = linspace(0,pi,1000); tic,y = fofx(x);toc Elapsed time is 0.000493 seconds. </code></pre> <p>By way of comparison, try an inline function.</p> <pre><code>finline = inline('sin(x*k)','x','k'); tic,y = finline(x,2);toc Elapsed time is 0.002546 seconds. </code></pre> <p>A neat thing about a function handle is you can define it on the fly. Minimize the function cos(x), over the interval [0,2*pi]?</p> <pre><code>xmin = fminbnd(@(x) cos(x),0,2*pi) xmin = 3.14159265358979 </code></pre> <p>There are many, many other uses for function handles in MATLAB. I've only scratched the surface here.</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