Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Kuba, m_goldberg, Yves Klett, bobthechemist, gpap Apr 3 at 15:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
@Kuba Right, that looks like the same question to me. Should I do anything? –  Bob2Alice Apr 3 at 12:57
    
Not necessarily, it will be a sign for future visitors. –  Kuba Apr 3 at 13:02

3 Answers 3

up vote 6 down vote accepted

You can do this :-

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

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

share|improve this answer
    
That certainly did the trick. Could you explain the syntax a bit? "## &[]" there's no way I would have figured this out on my own. –  Bob2Alice Apr 3 at 12:35
1  
Here is a reference: vanishing function –  Chris Degnen Apr 3 at 12:38
    
Great, thanks for the reference, I'll be able to figure it out from there. –  Bob2Alice Apr 3 at 12:39
    
@Bob2Alice Perhaps Table[If[Mod[k, 2] == 0, k, Unevaluated@Sequence[]], {k, 0, 10}] is clearer. –  Szabolcs Apr 3 at 14:42

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]]
share|improve this answer

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}
share|improve this answer

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