3
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ 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/… $\endgroup$ – Szabolcs Mar 7 '14 at 0:29
5
$\begingroup$

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&]
$\endgroup$
0
$\begingroup$
f[a_][b_] = a*b
g = f[2]
g[4]

(* 8 *)
$\endgroup$
  • $\begingroup$ I think this is not an analog of the MATLAB code he posted. $\endgroup$ – Szabolcs Mar 7 '14 at 0:25
  • $\begingroup$ @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. $\endgroup$ – ciao Mar 7 '14 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.