Starting in Release 2009a, str2func lets you create a handle to anonymous function. Before that, you need to construct an anonymous function from literal strings, or using some ugly code involving eval.
Contents
The Past
Since the introduction of anonymous functions in MATLAB version 7, you could create an anonymous function like this:
multiplier = 17; myfactor = @(x) multiplier*x;
The applying the function does what you expect.
x = rand(1,4) y = myfactor(x)
x =
0.42176 0.91574 0.79221 0.95949
y =
7.1699 15.568 13.468 16.311
I have just created a function that, when applied, multiplies its input by the value defined by multiplier (its value when myfactor was created).
multiplier = 42 y = myfactor(x)
multiplier =
42
y =
7.1699 15.568 13.468 16.311
Creating an Anonymous Function Inside a Function
Suppose I want to create an anonymous function, inside another function. And the information for the function to create is passed into the function. You can run into a problem if the function inside which you are creating the anonymous function happens to have some name, perhaps a subfunction, that is the same as the user input name. Using a solution involving eval would pick up the reference to the subfunction instead of the intended function outside the scope of the file. Here's an example.
function anon = myfun(X,fun)
anon = str2func(['@(',X,')',fun,'(',X,')']);function meshgrid disp(17)
What happens if you try to call myfun with fun = 'meshgrid'
anon = myfun('x,y','meshgrid');If you now use anon, e.g., [a,b] = anon(x,y), you will get the version of meshgrid on your path, not the one local to myfun. If instead you change str2func in myfun to eval, then anon(x,y) will use the subfunction meshgrid, which you most likely didn't intend, and certainly a user of your code would be surprised.
Does This Help?
Does this extended functionality in str2func help you with any of your applications? Let me know here.
Get
the MATLAB code
Published with MATLAB® 7.8



Hi Loren,
Yes, I’m already using this functionality in 2009a instead of my old kludgy eval method. Thanks to the team for extending this functionality and making it consistent with function handles.
Thanks,
Kieran
what a pity!I only have 2008b.^_^
Hi Loren,
I am looking for some way of creating function handle out of vectors of data. Situation is like this:
x= vector of independent variable (say, -5 to 5)
f= vector of dependent variable (computed per some complicated routine)
I need:
hf(x)= function handle that will output values of f for given x.
I know that I could find positions in x-vector closest to input and interpolate value of f from those positions. But I wish to do it in more elegant and function-independent way.
Can you please point me to right approach?
thanks
Shalin
Shalin-
Take a look at interp1 or spline perhaps.
–Loren
Hi Loren,
After a bit of thought I came up with this, which works. But let me know if there are other solutions.