6
$\begingroup$

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]
$\endgroup$
4
  • 3
    $\begingroup$ True? btw, what does && , mean, please pay attention. p.s. Switch would be more handy here, take a look at Piecewise too. $\endgroup$
    – Kuba
    Commented Mar 15, 2018 at 11:02
  • $\begingroup$ && means 'and'. Also || means 'or' as I know $\endgroup$ Commented Mar 15, 2018 at 11:08
  • 1
    $\begingroup$ I was concerned about , after &&. $\endgroup$
    – Kuba
    Commented Mar 15, 2018 at 11:18
  • $\begingroup$ Piecewise is working. Thank you! $\endgroup$ Commented Mar 15, 2018 at 11:21

4 Answers 4

18
$\begingroup$

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.

$\endgroup$
2
  • 1
    $\begingroup$ Sorry to nitpick, but you should test for integers in the third line. $\endgroup$
    – Kiro
    Commented Mar 15, 2018 at 13:36
  • 2
    $\begingroup$ @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. $\endgroup$
    – John Doty
    Commented Mar 15, 2018 at 14:15
4
$\begingroup$
f[x_Integer, y_Integer] :=Which[x == 1 && y == 0, 77, x == 0 && y == 1, 66, True, 0]
$\endgroup$
3
$\begingroup$

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.)

$\endgroup$
2
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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