4

Is there a way to use If statements with Table? To give a kind of ridiculous example that captures to spirit of what I'm trying to do, and I'm aware there are much better ways to do this, let's say we want to make an array of even values from zero to ten:

Table[If[Mod[k,2]==0,k],{k,0,10}]

The output is:

{0, Null, 2, Null, 4, Null, 6, Null, 8, Null, 10}

We could then delete the NULL entries and have our list of even values from zero to ten. However, how is this actually properly so that we don't have any NULL statements in the output from Table?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Bob2Alice
  • 127
  • 1
  • 1
  • 7

3 Answers3

9

You can do this :-

Table[If[Mod[k, 2] == 0, k, ## &[]], {k, 0, 10}]

{0, 2, 4, 6, 8, 10}

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
4

For variety's sake (and because I like Sow and Reap)...

Reap[Do[If[Mod[k, 2] == 0, Sow[k]], {k, 0, 10}]][[2, 1]]
Ymareth
  • 4,741
  • 20
  • 28
3

There are many alternatives to If in Mathematica. One that you might use is rule replacement:

Table[Mod[k, 2] /. {0 -> k, _ -> Sequence[]}, {k, 0, 10}]
{0, 2, 4, 6, 8, 10}

Another is that you might write your own function that does exactly what you want, because Mathematica's Hold-related attributes allow you to write many control structures as if they were ordinary functions:

Attributes[when] = HoldRest;

when[True, value_] := value;
when[False, _] = Sequence[];

Table[when[Mod[k, 2] == 0, k], {k, 0, 10}]
{0, 2, 4, 6, 8, 10}
Pillsy
  • 18,498
  • 2
  • 46
  • 92