Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the Null symbol in a Table in Mathematica?

I need to use If inside of a Table loop, e.g. Table[If[i< 3, i], {i, 5}] will give {1, 2, Null, Null, Null}

But I want the result to be {1,2}.

Any fix for this?

EDIT:
What if we consider Table[If[i< 3, f[i]], {i, 5}] which gives {f[1], f[2], Null, Null, Null}

like image 752
Osiris Xu Avatar asked Jan 16 '12 08:01

Osiris Xu


2 Answers

Concisely:

Table[If[i < 3, i, ## &[]], {i, 5}]

This works because the function ## & does not immediately evaluate.

## & is a "vanishing" function.

{1, 2, ## &[], 3, 4}
----> {1, 2, 3, 4}

See SlotSequence for more information.

like image 52
Mr.Wizard Avatar answered Oct 01 '22 14:10

Mr.Wizard


If you need to remove it from an existing list, you can use

DeleteCases[list, Null]

or

list /. Null -> Sequence[]

(a bit more advanced).


Regarding your Table example above, first note that the second comma in If is unnecessary (and is even highlighted in pink):

list = Table[If[i < 3, i], {i, 5}]

To filter the table elements by a condition, you might want to use something similar to

list = Select[Table[i, {i, 5}], # < 3 &]

instead.


Finally, if you need to generate the list without ever adding rejected elements to it (to save memory), I suggest using Reap and Sow:

Reap@Do[If[i < 3, Sow[i]], {i, 5}]
list = %[[2, 1]]

I haven't actually verified the memory usage of this compared to a plain Table, and note that if you generate only numbers, which can be stored in a packed array, the Table construct may be more memory efficient. On the other hand if you generate a truly huge number of generic expressions, the majority of which will be rejected in If, Sow / Reap may be better.

like image 22
Szabolcs Avatar answered Oct 01 '22 16:10

Szabolcs