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}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With