# 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

## 2 Answers

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:= f = # + z &
Out= #1 + z &

In:= f
Out= 3 + z

In:= z = 2
Out= 2

In:= f
Out= 5

In:= z = 3
Out= 3

In:= f
Out= 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
g

(* 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