2
$\begingroup$

I have a list of points

myList={{x_1,y_1},{x_2,y_2},...,{x_n,y_n}}

I want to plot not all the points of this list but to plot every $k$ points. For example, if I wanted to plot every $k=2$ points, the plot will contain only the points:

{{x_1,y_1},{x_3,y_3},{x_5,y_5},...}

or

{{x_2,y_2},{x_4,y_4},...}

It doesn't matter if Mathematica plots the odd points or the even points.

Another example is if I wanted to plot every $k=3$ points, the plot would contain only

{{x_1,y_1},{x_4,y_4},{x_7,y_7},...}

Question. Is there a direct way of doing this in Mathematica, without creating manually another list from myList?

$\endgroup$
7
$\begingroup$

You can use Part (also written [[...]]) to get what you want. For example,

myList= Table[{i, i}, {i, 1, 20}];

ListPlot[myList]
ListPlot[myList[[1;;-1;;2]]] (* every second point *)
ListPlot[myList[[1;;-1;;3]]] (* every 3rd point*)
| improve this answer | |
$\endgroup$
  • 4
    $\begingroup$ Or simply, ListPlot[myList[[;; ;;2]]] or ListPlot[myList[[;; ;;3]]]. The 1 and -1 are default values and are not required. $\endgroup$ – JungHwan Min May 25 '16 at 21:06
4
$\begingroup$

The ways listed work perfectly well, but you can save yourself a couple of keystrokes just by doing

myList[[;;;;2]]

If you don't provide starting and ending points for the first ;;, Mathematica is kind enough to assume that you want to go from the beginning (1) to the end (-1). For my tastes, at least, this looks a little nicer too. (It'll auto-format inside the program in a way that makes it a little easier to read than it's rendered here:)

enter image description here

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.