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

Using an If loop in Mathematica

  1. Oct 1, 2012 #1
    Dear all,

    I have a list of pairs say Li={{a,x},{b,y},{c,z}...}. I want to eliminate from this list all pairs that have their second part i.e the x, y, z.....>1 and I was thing of using an If loop. Can anyone tell me how please...



    Thanks....
     
  2. jcsd
  3. Oct 1, 2012 #2
    There is probably a more elegant way of doing it (it wouldn't surprise me if Mathematica has some built in function for this), but this should get you started:

    Code (Text):

    L2 = {};
    Do[
        If[Li[[i, 2]] <= 1, AppendTo[L2, Li[[i]]]]
        ,{i, Length[Li]}]
    L1 = L2;
     
     
    Last edited: Oct 1, 2012
  4. Oct 20, 2012 #3
    question : For each number k from 1 to 10, print half the number if k is even and twice the number if k is odd.
    <I think this question involving loop but i ddnt how to solve it. anyone ?>
     
  5. Oct 20, 2012 #4
    (*One built in function to eliminate pairs matching a condition using pattern matching*)

    In[1]:= v={{1,7},{2,-5},{3,0},{4,9}};DeleteCases[v,{x_,y_/;y>1}]
    Out[2]= {{2,-5},{3,0}}

    (*one method of printing using a For*)

    In[3]:= For[k=1,k≤10,k++,
    If[EvenQ[k],Print[k/2],Print[2k]]
    ]

    From In[3]:= 2
    From In[3]:= 1
    From In[3]:= 6
    From In[3]:= 2
    From In[3]:= 10
    From In[3]:= 3
    From In[3]:= 14
    From In[3]:= 4
    From In[3]:= 18
    From In[3]:= 5

    (*another method using pattern matching*)

    In[4]:= k=.; (*clear that value assigned to k*)
    Range[10]/.{k_/;EvenQ[k]->k/2,k_/;OddQ[k]->2k}

    Out[5]= {2,1,6,2,10,3,14,4,18,5}
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Using an If loop in Mathematica
  1. Mathematica to use it (Replies: 2)

  2. Mathematica looping (Replies: 3)

Loading...