I would like to select a small subset of rows of a table based on a predicate involving multiple columns.

Here's a small example of what I want using For[]:

For[n = 10, n < 1000, n++, 
 If[n^3 < 15 n^2, Print[n, " ", n^3, " ", 15 n^2]]

10 1000 1500

11 1331 1815

12 1728 2160

13 2197 2535

14 2744 2940

I understand that using For[] is not good Mathematica style, so I tried to do this with Table[] and Select[]. So although Table[] will generate all the rows, I can't seem to get Select[] to filter out the rows that I don't want.

How would one do this without using For[] in good Mathematica style?

  • $\begingroup$ Do you already have a table given (e.g. some dataset from another source) or do you want to build it? $\endgroup$ Commented Sep 27, 2018 at 22:25
  • $\begingroup$ @HenrikSchumacher I'm going to create the rows on the fly, but only want to output the ones matching the predicate. $\endgroup$ Commented Sep 27, 2018 at 22:38

1 Answer 1


If you have already have a table tab given and you want to filter it, probably the easiest way (but not exactly the most efficient) is by using Select:

tab = Table[{n, n^3, 15 n^2}, {n, 10, 1000}];(* creating the table *)
result = Select[tab, X \[Function] X[[2]] < X[[3]]]

{{10, 1000, 1500}, {11, 1331, 1815}, {12, 1728, 2160}, {13, 2197, 2535}, {14, 2744, 2940}}

If you want to build the table result but if you do not want to build the full input table tab (e.g., for memory reasons), you can also use Sow and Reap:

result = Reap[
  Do[If[n^3 < 15 n^2, Sow[{n, n^3, 15 n^2}]], {n, 10, 1000}]
  ][[2, 1]]

{{10, 1000, 1500}, {11, 1331, 1815}, {12, 1728, 2160}, {13, 2197, 2535}, {14, 2744, 2940}}

Unless the number of n to try is not too large, the first method will be faster, because it utilizes a packed array. The latter method needs some overhead to manage a more flexible data structure.

Well, the thing about packed arrays is probably too much detail for you at the moment...

You use Print to print the results into the notebook. If you want to use them later, you should store the results in an array as I did in the examples.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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