Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help with "Which[] in a For loop using Mathematica

Tags:
  1. Sep 12, 2014 #1
    Hello,
    I am a novice in Mathematica, but insisting to learn it. I would appreciate help in solving the following problem:

    (*a=1;Which[a==1,x,a==2,b]*)

    list := List[1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 32, 10]

    For[i = 1, i < 4, i++,

    a = list[];

    Print[a];

    Print[list[]];

    Which[a == 1611, x, a == 1612, y];

    Print[%]]


    When I run the code, I get the following result:

    1611

    1611

    Null

    1612

    1612

    Null

    1613

    1613

    Null

    While I think I am faithfully mimicking the Mathematica "Which statement" quoted above, it seems including the "Which" statement in the "For" loop does not make work as intended. Is this right? If not, please point out my mistake.

    Best Regards
     
  2. jcsd
  3. Sep 14, 2014 #2
    Compare these two

    Code (Text):
    In[3]:= q = 1611;
    Which[q == 1611, x,
     q == 1612, y]

    Out[4]= x

    In[5]:= q = 1611;
    Which[q == 1611, x,
      q == 1612, y];
    In the first the value of the Which is x. In the second the semicolon, after after that Which, discards the output and the result is simply nothing (or Null). So in your example you are Printing the result returned from the previous expresssion, the Which, and that is nothing or Null. Thus Null is Printed.

    If you changed your code to be

    Code (Text):
    w = Which[a == 1611, x,
       a == 1612, y];
    Print[w]
    then you might get what you are hoping for.
     
  4. Sep 14, 2014 #3
    Thank you so much. It works for me. :)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Help with "Which[] in a For loop using Mathematica
  1. Mathematica looping (Replies: 3)

Loading...