I have a function that generates a list of numbers and variables .
e.g.
F[w]= {wx, wy, 5, 0}
I want to select all non-zero elements i.e. {wx,wy,5}.
I have a function that generates a list of numbers and variables .
e.g.
F[w]= {wx, wy, 5, 0}
I want to select all non-zero elements i.e. {wx,wy,5}.
For the "heck" of it and to wrap it all up:
Let's create a sufficiently large list and test for performance.
SeedRandom["115522"]; (* make this replicable *)
list = RandomVariate[ EmpiricalDistribution @ Range[10], 1*^6 ];
expressions = {
"list /. _?PossibleZeroQ\[Rule]Nothing",
"Select[ list, Not@*PossibleZeroQ ]",
"DeleteCases[list,0|0.]",
"Cases[list,Except[0|0.]]",
"list /. 0|0. \[Rule] Nothing ",
"Select[ list, #!=0& ]",
"SparseArray[list][\"NonzeroValues\"]"
};
tfunc = Function[ expr,
expr // RightComposition[
ToExpression,
Timing,
First
]
];
runtimes = Map[ tfunc, expressions ];
BarChart[ { runtimes },
ChartLegends -> { Style[#, FontFamily -> "Consolas"] & /@ expressions },
LabelingFunction -> (Placed[PaddedForm[#, {3, 2}], Above] &),
PlotTheme -> "Business"
]
PossibleZeroQ (non-surprisingly) does come at a price.
– gwr
May 19 '16 at 17:06
SparseArray[list]["NonzeroValues"]
Should perform quite well on large lists...
Cases[{wx, wy, 5, 0, 0.}, Except[0 | 0.]]. – march May 19 '16 at 15:50DeleteCases[{wx, wy, 5, 0, 0.}, 0|0.]is probably more natural that my original.) – march May 19 '16 at 16:08{wx, wy, 5, 0, 0.} /. {0 | 0. -> Sequence[]}. – N.J.Evans May 19 '16 at 16:08list /. _?PossibleZeroQ -> NothingorSelect[ list , Not @* PossibleZeroQ ]– gwr May 19 '16 at 16:18Pick[#, Chop[#], Except[0, _?AtomQ]] &@{wx, wy, 5, 0, 0.}or (see here, kglr in 'comments'):Pick[#, Chop[#], Except[0 | _List]] &@{wx, wy, 5, 0, 0.}]– user1066 May 19 '16 at 19:51