MathGroup Archive 2000

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Conditionals with multiple tests?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg24151] Re: [mg24104] Conditionals with multiple tests?
  • From: BobHanlon at aol.com
  • Date: Wed, 28 Jun 2000 02:12:03 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

In a message dated 6/27/2000 1:05:15 AM, siegman at stanford.edu writes:

>Let's say I want to assign values to three variables p1, p2, p3 that 
>will depend on five different (and nonoverlapping) tests test1 to test
>5.
>
>One way to do this is obviously
>
>      p1 = Which[test1, value11, test2, value12, . . . ]         
>      p2 = Which[test1, value21, test2, value22, . . . ]   
>      p3 = Which[test1, value31, test2, value32, . . . ]
>
>But a more compact and (for me anyway) neater approach is
>
>   Which[test1, p1=value11; p2=value21; p3=value31,
>              test2, p1=value21; p2=value22; p3=value32,
>              test3, . . . 
>              test4, . . . 
>              test5, . . . ]
>
>Is this form legal?  That is, can one use:
>
>      Which[test1, expr1, test2, expr2, . . .]
>
>where expr1, expr2, . . . may be compound expressions?
>
>(I would say that The Mathematica Book is not at all clear on this 
>point, as regards either Which[] or If[].)
>
>If not, is there a legal way to implement the basic objective?

As long as a test is not encountered which gives neither True nor False, the 
syntax is very flexible. These four different forms work:

Clear[p1, p2, p3];

{p1, p2, p3} = Which[True,  {value11, value21, value31},
    True,   {value12, value22, value32} ]

{value11, value21, value31}

{p1, p2, p3} = Which[False,  {value11, value21, value31},
    True,   {value12, value22, value32} ]

{value12, value22, value32}

Which[True,  {p1, p2, p3} = {value11, value21, value31},
  True,   {p1, p2, p3} = {value12, value22, value32} ]

{value11, value21, value31}

Which[False, {p1, p2, p3} =  {value11, value21, value31}, 
  True,  {p1, p2, p3} =  {value12, value22, value32} ]

{value12, value22, value32}

Which[True,  {p1 = value11, p2 = value21, p3 = value31} , 
  True,   {p1 = value12, p2 = value22, p3 = value32}]

{value11, value21, value31}

Which[False,  {p1 = value11, p2 = value21, p3 = value31} , 
  True,   {p1 = value12, p2 = value22, p3 = value32}]

{value12, value22, value32}

Which[True,  p1 = value11; p2 = value21; p3 = value31 , 
  True,   p1 = value12; p2 = value22; p3 = value32]

value31

{p1, p2, p3}

{value11, value21, value31}

Which[False,  p1 = value11; p2 = value21; p3 = value31 , 
  True,   p1 = value12; p2 = value22; p3 = value32]

value32

{p1, p2, p3}

{value12, value22, value32}


Bob Hanlon


  • Prev by Date: Re: Gradient in FindMinimum
  • Next by Date: Re: Piecewise functions definition and usage
  • Previous by thread: Re: Conditionals with multiple tests?
  • Next by thread: Re: Conditionals with multiple tests?