5
$\begingroup$

When I write

Table[If[x <= q, 0, q], {q, 1, 3}]

the output is

{If[x <= 1, 0, q], If[x <= 2, 0, q], If[x <= 3, 0, q]}

rather than, as I would expect,

{If[x <= 1, 0, 1], If[x <= 2, 0, 2], If[x <= 3, 0, 3]}

What am I doing wrong?

$\endgroup$
6
$\begingroup$

Table is not replacing anything - as noted in the documentation, Table works similar to Block in that it temporarily assigns a value to the iterator variable, after which the expression in the body is evaluated. In your case, you are seeing the effects of the HoldRest attribute of If: Since the condition is neither True nor False, If stays unevaluated, which means the second and third argument stay as they are, no value is inserted.

To fix this, you can use e.g. With to inject the values into the held parts of the expression:

Table[
 With[{q = q},
  If[x <= q, 0, q]
  ],
 {q, 1, 3}
 ]
(* {If[x <= 1, 0, 1], If[x <= 2, 0, 2], If[x <= 3, 0, 3]} *)
| improve this answer | |
$\endgroup$

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.