10

What I am wondering is how do you perform multiple lines when using the If statement. I know the following is not proper Mathematica code, but how would I do this in Mathematica?

if(x<1,
 y=2x;
 z=2y
else
 y=x/2;
 z=y/2
)

Mr. Wizard help:

It does work. For example:

In[181]:= x = 0; If[x < 1, y = 2 x; z = 2 y, y = x/2; z = y/2]

Out[181]= 0

Another example:

In[182]:= x = 2; If[x < 1, y = 2 x; z = 2 y, y = x/2; z = y/2]

Out[182]= 1/2

But if the expressions are quite long and complicated, maybe this approach?

In[180]:= x = 2; If[x < 1,
 {
  y = 2 x;
  z = 2 y
  },
 {
  y = x/2;
  z = y/2
  }
 ]


Out[180]= {1/2}
David
  • 14,883
  • 4
  • 44
  • 117

1 Answers1

15

It seems this question is now purely about style and will probably be closed. However I think you may be looking for this:

If[x < 1,
 (
  y = 2 x;
  z = 2 y
 ),
 (
  y = x/2;
  z = y/2
 )
]

Though I would prefer (hat tip to WReach's comma placement):

If[x < 1,

  y = 2 x;
  z = 2 y

, y = x/2;
  z = y/2

]

If your code is very long I suggest you modularize it, i.e.:

doIfTrue[] := (
  y = 2 x;
  z = 2 y
)

doIfFalse[] := (
  y = x/2;
  z = y/2
)

If[x < 1, doIfTrue[], doIfFalse[]]

Or a more functional equivalent:

doIf[] /; x < 1 := (
  y = 2 x;
  z = 2 y
)

doIf[] /; ! x < 1 := (
  y = x/2;
  z = y/2
)

doIf[]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371