Functions returning handles to subfunctions

From NA-Wiki

Jump to: navigation, search

This page puts the spotlight on a feature that i rarely used in the matlab language -- that a function may share its subfunctions to the world by returning handles to them.

Consider the following function:

%%% begin file
function f = func(i)
switch i
 case 1
  f = @fun1;
 case 2
  f = @fun2;
  error('no such function');

function f = fun1(x)
f = sin(x);

function f = fun2(x)
f = cos(x);
%%% end file

A calling context can then do something like

x = linspace(0,2*pi,60);
g = func(1);
h = func(2);
plot(x,g(x)) %subfunction fun1 is evaluated
plot(x,h(x)) %subfunction fun2 is evaluated

To see how this can be handy, consider the following example: We write a curve fitting routine that fits a function (which contains a parameter) to some data set. But the routine shall also decide which is the best type of function to fit (exponential, linear, log, etc.). Then one could have the curve fitting routine return both the parameter value that gives the proper fit, and a handle to evaluate the function.

Personal tools