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.
I’m all in favor of improved capability that eliminates the need to use eval. eval always seems to be a technique to be used in desperation only.
However, I’ve never seen the advantage of using either an anonymous or a nested function. Using these techniques seems to less clear than writing a well documented, well commented stand alone function which I generally will write in a separate .m file. For deployment, I’ll concatenate each file into one file to end up with a primary function with subfunctions & move forward from there.
I would love to see examples where anonymous functions gave a significant advantage in code clarity. In browsing the world of MatLab, I found a comment from Markus, ” . . . they are cryptic to read and painfully slow . . .” & I find that he & I frequently agree on these issues.
Although performance is always an important issue, clarity is always much more important for us.
Our primary issue & concern is maintenance of the code & the 1st line of defense is to use very clear, well documented code. We frequently avoid techniques that can make for very compact code because we are concerned that the guy who inherits the code might have trouble understanding what the code did. The only regular exception to this is that we will frequently vectorize rather than using for loops.
OysterEngineer-
I understand you don’t care for nested and anonymous functions. I find them very useful AND readable. Anonymous are particularly good when I don’t have a function lying around and can create it easily. The workflow for me gets harder if I have to stop and create another function, increasing the odds that I won’t bundle up all function necessarily at once. And if I’m using a script, I don’t have the luxury of adding a subfunction.
I found nested and anonymous functions mysterious for about the first 3 weeks I used them. I could see how they worked, would get confused, tinker and try things and make them work without really understanding them, and then one day I got it. Same way I was ultimately able to learn to swim butterfly, by the way. Persistent near drowning for 3 weeks, and then I got the right rhythm.
–Loren
Mmmmm. . . I wonder how I can duplicate your 3 weeks of learning.
Your comment about the effort to make a separate, stand alone function is interesting. One of the advantages I see with a stand alone function is that it is best if you exercise the discipline to write it properly, even if it requires sub-functions.
And, I don’t mean to imply that anonymous functions aren’t “proper.”
My current view is that there must be something really attractive about anonymous functions or else the smart folks at The MathWorks wouldn’t have developed them. I just wish I understood what those developers saw that was so attractive.
OysterEngineer-
Maybe an idea is the next time you write a function that has some extra stuff it MIGHT need because of one of the inputs, consider using that as an opportunity to write it as nested or anonymous. Like a quad function, for example. It takes a function and possibly some extra args for that function. That’s a case ripe for one of these constructs.
–Loren
hi Loren,
Anonymous functions are a great construct that I use often, particularly when processing cells/arrays, via the cellfun and arrayfun (and recently the bsxfun) functions.
Unfortunately, I find the anon function limitation, that prevents non-trivial constructs, very disturbing.
For example, if I want to use the well-known IFF function (if flag then return 1 else return 2), I need to define my own function/subfunction that implements it and then use its handle. Instead, I would much rather use the following simple integrated one-liner:
cellfun(@(x)(if (x==1) result=2; else result=3; end), data)
or similarly:
myfunc = @(x) (if (x==1) result=2; else result=3; end);
-Yair
Yair’s comments about when he finds anonymous functions useful reminded me of something I did just last week. I had a structure array, data, that contained several hundred elements. The structure fields included test, time, release, description, and legend.
I needed to pull a subset of the data. Specifically, I needed all the structure elements whose “test” field was the string “inverse_real”.
Here’s the solution using an anonymous function and arrayfun.
I would have been pretty annoyed if I had to create a two-line M-file and put it somewhere on my path just to be able to accomplish this.
Steve,
A couple things. Reading between the lines, it appears that your use of this feature is from the command line, rather than writing a stand-alone function to process the data. i.e., you are using MatLab in what I call its supper, wizbang desktop calculator mode. Then, you wanted to inspect the data_subset in the workspace after you had done this command line processing. Am I guessing correct?
Next, from a first reading of the FRP for arrayfun, I can’t see from the Description how you are using legal syntax. Only after reading it several times & jumping over to the FRP for function_handle do I pick up on the subtle detail that your 1st argument in arrayfun is an in-line generation of a function handle. The fact that that 1st argument is a function handle is almost hidden in plain sight.
Like I said, this is all very confusing to us. Several of us out here discussed this a bit and we are all equally confused.
The clearest way to generate your index variable, select, is to do it inside some for loops. Isn’t this what you are after?
for ii = 1 : size(data, 1) for jj = 1 : size(data, 2) select(ii, jj) = strcmp(data(ii, jj).test, 'inverse_real'; end end data)subset = data(select);I suppose for my code, you need to know that data has 2 dimensions. But, usually I know the data well enough that this isn’t a problem.
I do stuff like this from the command line all the time. Or, I just open an editor window, type it out, highlight it & do a Evaluate Selection.
Another point.
The style of putting the argument list for an anonymous function ahead of the function name rather than after it doesn’t make any sense to us. All normal functions in the world of MatLab have the input arguments after the function name.
Why is it reversed for anonymous functions?
OysterEngineer—All function handles are introduced with the “@” character. This is completely consistent, so I don’t really see that the appearance of a function handle in the call to arrayfun is “hidden in plain sight.” Also, I find your code as distasteful as you apparently find mine.
;-)
Steve,
I didn’t mean to imply that your code is distasteful, I just can’t understand what it is doing at a glance. Since I’m one of the more experienced MatLab users around here, if I can’t understand a coding technique, I certainly can’t expect my co-workers to understand it. If you think my code example is harder for a novice to follow, tell me why.
My comment regarding the function handle being hidden in plain sight was only in regards to the way the FRPs for these functions of functions are written.
A life-long dear friend of mine (he & I were best men at each other’s weddings) has worked for a career as a code developer. When I complain to him about code that I can’t understand, he bluntly counters that that is the reason why professional developers are needed.
But, that model doesn’t work for MatLab. We recognize that all the technical computing functionality we write in .m code could be provided by some custom application written in C or whatnot. But, the advantages writing it in MatLab outweigh the disadvantages of having amateurs writing the code. But, we still have to verify that the code does the correct thing & that requires that we be able to read & understand the code.
Like I said before, I would love to understand fully why you smart developers at The MathWorks think function handles & anonymous functions are attractive. You clearly see something that we don’t. And, this isn’t at all like the other type of technical computing decisions we make in the world of MatLab.
For example, I may choose to estimate transfer functions from recorded data using a CZT based routine rather than an FFT based routine. I understand how to solve the problem each way & make the decision based on subtle points.
In the case of anonymous functions, my co-workers & I just don’t get it. If as Loren says, a user has to play with it for 3 weeks to understand it, then why can’t you guys write up a nice training package that leads the user thru this so they can make the decision about using the technique from a position of knowledge? Instead, I’m forced to not even consider the technique only because I can’t imagine why this is attractive.
OysterEngineer—You raise a number of good questions that I’m interested in addressing. It will probably be a few days, though, given what the calendar on the screen in front of me looks like at the moment. I might about it on my blog. If I do that, I’ll post a pointer here.
OysterEngineer-
More thoughts from me…
* Another reason I like nested and anonymous functions. This particular discourse will concentrate on anonymous functions mostly, but nested and anonymous functions are so closely related that they points work for both.
Nested/anonymous functions allow for more natural APIs/interfaces. Here’s a quick example. If I want to work with a bunch of lines, ones for which I don’t know the slope and intercept, I have to write a function that takes 3 inputs (x,m,b). But if what I am doing with these lines is integrating, for example, I really need to have the function be a function of x alone, and not include slope/intercept.
No programming languages that I am familiar with allow you to separate parameters (slope/intercept) from unknowns (or variables). They are all just variables. But, if I have a line defined as a function of x, I can ask all kinds of questions about it without having to myself know slope and intercept. For that matter, I can substitute something that’s not strictly a line. Suppose I want to next see what happens with a quadratic. If I use the paradigm of having to write a function, I have to write it now to include, 3 terms, and I have to change my integrator to accept 3 optional arguments, etc.
More elegantly, I can supply a function handle that has only x as an input, and who cares what the underlying function is. That anonymous function carries with it all the information it needs, and the function I send it to doesn’t need to know anything other than it is a function of x. Gets all the parameter messiness out of the way.
* Finally, I recommend you “put some skin in the game” - i.e., read (or reread) posts from this blog under the category Function Handles, download the code or copy/paste it into an editor and try it. There are examples in the documentation. Copy/paste them into files, run them, go through them with a debugger, etc. I don’t think you can replicate my 3 weeks of learning by reading a doc alone. Take the plunge.
–Loren
I guess the types of technical computing problems you work on are so different from the ones I work on that I’m having trouble following your thinking.
Yes, I’ll put some effort into this. Sounds like a fun way to spend the Thanksgiving weekend.
OysterEngineer,
I second Loren’s suggestion on giving anonymous and nested functions a try. It took me a little while to get used to the new syntax for anonymous function, but just like any other MATLAB syntax, I am completely used to it now. I had VERY little programming experience when I started using MATLAB (I may have programmed a little in BASIC), so the learning curve was steep, but after that, MATLAB code was MATLAB code, including anonymous functions.
Another relevant example is the new Object Oriented Programming capability that was introduced in R2008a. It’s a completely new programming construct, which may seem extremely foreign to a traditional MATLAB user. I was one of those people. I had no experience in object oriented programming, so I was very confused. I think it took me about a year to get my head around it. Now, it feels very natural, and I love it. It changed how I code in MATLAB, and I can create more sophisticated applications with it.
I think we should not dismiss a particular feature just because it is a foreign concept or syntax. Although, I do agree that there should be added benefits for any new programming constructs. I hope that some of the discussions in this post, as well as the other posts by Loren, will convince you of the benefits of anonymous functions. I do recommend giving them a try.
p.s. BTW, I find Steve’s example with the anonymous function so much easier to understand, because I know how to interpret that syntax. This is how you would read it:
“Do the following for each element of the structure array ‘data’: compare field ‘test’ of the structure with string ‘inverse_real’. Store the results to an array ’select’.”
hi again Loren - I think my small question (#10 above, http://blogs.mathworks.com/loren/2009/03/13/using-str2func-for-anonymous-function-handle-creation/#comment-30797 ) may have gotten lost in the Oyster/Steve discussion. Could you please revisit?
Suggestion: perhaps enable return to accept arguments:
myfunc = @(x) (if (x==1) return(2); else return(3); end);
This would seem to be entirely backward compatible with existing code and may be useful for Matlab functions in general (not just anonymous):
function [a,b] = myfunc(data)
% do some useful computation
return (result1,result2);
end
Thanks,
Yair
Yair-
Sorry for the oversight - definitely not intentional. Please use the link on the right to make an enhancement request via technical support. I don’t think it is entirely compatible since in a regular function, the function has its return args listed in the program. And now return would depend on position. But would it obey nargout? And what if the results returned were different for different values of nargout? Clearly, I haven’t thought about this enough to evaluate if it’s even realistic.
In your example with anonymous function, you can get the same result now with
myfunc = @(x) (x==1)*2 +(x==2)*3 >> myfunc = @(x) (x==1)*2 +(x==2)*3 myfunc = @(x)(x==1)*2+(x==2)*3 >> myfunc([1 3 2]) ans = 2 0 3–Loren