Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the oddly indexed elements in a list in mathematica

How to get the oddly indexed elements in a list? I am thinking of Select, but did not find anything returning an element's position, especially considering there are repetitive elements in the list.

Also in general, how to select those elements whose indices satisfy some certain conditions?

like image 723
Qiang Li Avatar asked Jan 27 '11 05:01

Qiang Li


3 Answers

Here's a few more in addition to @belisarius's answer, which don't require computing Length[lis]:

Take[lis, {1, -1, 2}]

lis[[1 ;; -1 ;; 2]]

You can often use -1 to represent the "last" position.

like image 139
Michael Pilat Avatar answered Nov 13 '22 17:11

Michael Pilat


There are a lot of ways, here are some of them:

In[2]:= a = Range[10];le = Length@a;

In[3]:= Table[a[[i]], {i, 1, le, 2}]

In[5]:= Pick[a, Table[Mod[i, 2], {i, 1, le}], 1]

In[6]:= a[[1 ;; le ;; 2]]

In general, with Pick[] (as an example) you can model any conceivable index mask.

like image 26
Dr. belisarius Avatar answered Nov 13 '22 19:11

Dr. belisarius


For some reason the terse form of Span has been omitted from the answers.

Range[20][[;;;;2]]
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}

Quoting the documentation:

;;;;k 
from the beginning to the end in steps of k.  
like image 37
Mr.Wizard Avatar answered Nov 13 '22 17:11

Mr.Wizard