I am trying to use the If so that when the 1st argument is true, it plots a graph of a function and when false, returns 0. I know that the format of an if statement is If[x, TRUE, FALSE], but I don't know how the input works when I want to check the function for x within the If expression so that I can graph that function when it is true.

New contributor
Bob is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

This should show you how to do it.

  If[x, Plot[Sin[2 π t], {t, 0, 1}], 0],
  {x, {True, False}, Setter}]



Or, perhaps, this will be closer to the answer you are looking for:

With[{x = True}, If[x, Print[Plot[Sin[2 π t], {t, 0, 1}]], 0]]

The above will will show your plot, and this will return zero.

With[{x = False}, If[x, Print[Plot[Sin[2 π t], {t, 0, 1}]], 0]]

In a notebook it looks like this:



Plot works with logical statements, for instance


Also see Piecewise or Switch instead of nesting Ifs for multiply defined functions.

  • $\begingroup$ When I try to test the input, it results in an output of the graph even if x is false for some reason. $\endgroup$ – Bob yesterday
  • $\begingroup$ Plot f1(x) between x = -10 and x = +10, where f1(x) = +x2 when x is positive, f1(x) = -50 when x is -2 or smaller, and f1(x) = 0 otherwise $\endgroup$ – Bob yesterday

Your Answer

Bob is a new contributor. Be nice, and check out our Code of Conduct.

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.