Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Using str2func for Anonymous Function Handle Creation

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.




Published with MATLAB® 7.8


  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.