# Defining an anonymous function using another function but with fewer arguments

In MATLAB you can use an anonymous function with another function to define a new function with fewer arguments as long you define the excluded argument before, e.g.

z=1

f1=@(x,y) f(x,y,z)

x=2

y=3

f1(x,y)


Can you do that in Mathematica?

-
You'll find that working with anonymous functions is much more flexible and convenient in Mathematica than in MATLAB. Mathematica is a functional language an anonymous (or named) functions are essential to it. Look up Map, Fold, etc. and read this part of the docs: reference.wolfram.com/mathematica/tutorial/… – Szabolcs Mar 7 '14 at 0:29

In Mathematica the equivalent of that would be

f1 = f[#1, #2, 1]&


The key is using Function, for which & is a short notation.

Note that I inlined the value of z here manually, as this is the simplest way to achieve the behaviour of your MATLAB function.

Here's a subtle difference between MATLAB and Mathematica:

MATLAB would capture the value of z at the time you define your function, and any subsequent changes to z won't affect what the function does.

In contrast to this, Mathematica will simply use the symbol z, which will in turn evaluate to its global value. For example:

In[1]:= f = # + z &
Out[1]= #1 + z &

In[2]:= f[3]
Out[2]= 3 + z

In[3]:= z = 2
Out[3]= 2

In[4]:= f[3]
Out[4]= 5

In[5]:= z = 3
Out[5]= 3

In[6]:= f[3]
Out[6]= 6


Notice that: 1. you can have a symbolic z in Mathematica 2. changing the value of the global variable z affects what the function does.

If you want to inline the value of a global variable when defining the function (as MATLAB does), use With:

f = With[{t = z}, #+t&]

-
f[a_][b_] = a*b
g = f[2]
g[4]

(* 8 *)

-
I think this is not an analog of the MATLAB code he posted. – Szabolcs Mar 7 '14 at 0:25
@Szabolcs: I think you're right, your comment is more what the OP is looking for. The idea of defining some function based on an earlier global (or local) is so... yuck. – ciao Mar 7 '14 at 0:27