Message Boards Message Boards

0
|
3606 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How can I use 'If' statement to define an equation?

Hi all-

I am trying to define an equation one way under certain conditions and another way under different conditions. I am a little rusty with mathematica. Here is a simple example (not the actual equations I am using):

ClearAll["Global`*"];
b = 5;
If[a < b, pumpkin = 0, pumpkin = a + b]
Plot[pumpkin, {a, 0, 12}]

This is not behaving as I expected. Is there a different function I should be using, or did I make a small error?

Thanks for any input you can provide.

Cheers, Laura

POSTED BY: Laura McMullen
2 Replies

Hi Laura,

You are on the right way, but the syntax is not correct. There are multiple ways of doing this, the one closest to yours would be:

ClearAll["Global`*"];
b=5;
pumpkin[a_]:=If[a<b,0,a+b] 
Plot[pumpkin[a],{a,0,12}]

alternatively you could do it as:

ClearAll["Global`*"];
b=5;
pumpkin[a_]:=Piecewise[{{0,a<b},{a+b,True}}] 
Plot[pumpkin[a],{a,0,12}]

or shorter versions:

ClearAll["Global`*"];
b = 5;
Plot[Piecewise[{{0, a < b}}, a + b], {a, 0, 12}]
Plot[If[a < b, 0, a + b], {a, 0, 12}]

I would suggest you to use piecewise, as this is designed for making piecewise functions, If was not. You can also see that they plot slightly differently at the transition a=b

POSTED BY: Sander Huisman

Great, thank you Sander that was very helpful. I used Piecewise and it worked great.

POSTED BY: Laura McMullen
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract