How do I return a function as an output value in MATLAB?

function, matlab, return

Solution

Use function handles.

function f = functionReturner(u)
% creates the function x.^u to return as an example
f = @(x) x.^u;

If I save this function, then call functionReturner, the argument is itself a function.

f = functionReturner(3);
f(2.5)
ans =
       15.625

You can easily enough verify that 15.625 is indeed 2.5^3.

Problem

I am writing a function `makeFunction(data)`. I want it to return a function, not a matrix, vector, or scalar. How do I do this?

Original source