Loren on the Art of MATLAB

March 13th, 2009

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.


Get the MATLAB code

Published with MATLAB® 7.8

5 Responses to “Using str2func for Anonymous Function Handle Creation”

  1. Kieran replied on :

    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

  2. 钟梁 replied on :

    what a pity!I only have 2008b.^_^

  3. Shalin Mehta replied on :

    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

  4. Loren replied on :

    Shalin-

    Take a look at interp1 or spline perhaps.

    –Loren

  5. Shalin Mehta replied on :

    Hi Loren,

    After a bit of thought I came up with this, which works. But let me know if there are other solutions.

    hf = @(xi) interp1(x,f,xi)
    

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Loren: Hi Ghazanfar- Please look at the help for the function hist (and perhaps histc). They will do what you want...
  • Ghazanfar Ali: Hi Miss Loren I am in need of an algo to count cosecutive duplicate values in a one dimensional...
  • OysterEngineer: Clearly this is a complex topic & these pair of blogs show that The MathWorks are masters of the...
  • Tim Davis: I’ve often been puzzled about how sub-matrix-assignmen t works for full and sparse arrays: clear A =...
  • Loren: Paul- There *are* issues depending on the sizes of ii and jj. And it’s a bit complicated, but really...
  • Loren: Bob- You don’t say what happens when you run your code. Can you please explain more. It looks like you...
  • Loren: Kishore- It is not clear to me what you are trying to actually achieve. If you want to concatenate the 4...
  • Kishore: sorry, in the previous code mat2cell(c,[19 121],[19 134],[19 84],[19 107])
  • Kishore: Hi Loren, Why does the following not work? data_classwise = [19x121 double] [19x134 double] [19x84 double]...
  • Paul Jackson: Loren, Are there any aspects of empty matrices that may be tricky when they are used as indices into...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.