# How to define conditional function with Mathematica?

How to define conditional function $$f(x,y)$$ with the following result. If $$x=1$$ and $$y=0$$ then $$f=77$$, if $$x=0$$ and $$y=1$$, then $$f=66$$, if $$x$$ and $$y$$ are all other integer values then $$f=0$$. How to define in Mathematica phrase 'all other values'?

f[x_,y_]:=Which[x==1 && y==0, 77,
x==0 && y==1, 66,
"all other values of x,y", 0]

• True? btw, what does && ,  mean, please pay attention. p.s. Switch would be more handy here, take a look at Piecewise too.
– Kuba
Commented Mar 15, 2018 at 11:02
• && means 'and'. Also || means 'or' as I know Commented Mar 15, 2018 at 11:08
• I was concerned about , after &&.
– Kuba
Commented Mar 15, 2018 at 11:18
• Piecewise is working. Thank you! Commented Mar 15, 2018 at 11:21

I think it's easier just to define this straight up, rather than compute something procedurally.

f[1, 0] = 77;
f[0, 1] = 66;
f[_, _] = 0;


Mathematica is fundamentally an expression rewriting system, so telling it how to rewrite expressions directly like this is usually clearer, faster, and easier to debug.

• Sorry to nitpick, but you should test for integers in the third line.
– Kiro
Commented Mar 15, 2018 at 13:36
• @Kiro, of course one could do f[_Integer, _Integer] and perhaps that's what @Timur would like. However, my answer meets his specification: he did not state what should happen for non-integers, and his attempt suggests 0 was a general default. Commented Mar 15, 2018 at 14:15
f[x_Integer, y_Integer] :=Which[x == 1 && y == 0, 77, x == 0 && y == 1, 66, True, 0]


You can do this using Piecewise:

f[x_, y_] := Piecewise[{{77, {x, y} == {1, 0}}, {66, {x, y} == {0, 1}}}, 0]


(Piecewise takes as arguments an array of tupels {value,condition} and optionally a "default" value if all conditions are false.)

The null represents "all other values". You can replace it with anything you like.

f[x_, y_] := If[x == 1 && y == 0, 77, If[x == 0 && y == 1, 66, If[IntegerQ[x] && IntegerQ[y], 0, null]]]


Test it:

f[1, 0]


OUT: 77

f[0, 1]


OUT: 66

f[9, -2]


OUT: 0

f[9, 1.1]


OUT: null

f[1.2, Pi]


OUT: null