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}.

march
  • 23,399
  • 2
  • 44
  • 100
user40372
  • 51
  • 1
  • 2
  • 2
    Cases[{wx, wy, 5, 0, 0.}, Except[0 | 0.]]. – march May 19 '16 at 15:50
  • 5
    Possible duplicates where one should be marked duplicate probably: (42971) and (47214). – march May 19 '16 at 15:58
  • Also look at the proposed duplicates. There are other solutions that might be better, based on comments by the posters there. (Also, DeleteCases[{wx, wy, 5, 0, 0.}, 0|0.] is probably more natural that my original.) – march May 19 '16 at 16:08
  • 1
    You can also do {wx, wy, 5, 0, 0.} /. {0 | 0. -> Sequence[]}. – N.J.Evans May 19 '16 at 16:08
  • 1
    Another possibility which might be more general is list /. _?PossibleZeroQ -> Nothing or Select[ list , Not @* PossibleZeroQ ] – gwr May 19 '16 at 16:18
  • There is also pick. For example, Pick[#, 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

2 Answers2

12

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" 
]

enter image description here

gwr
  • 13,452
  • 2
  • 47
  • 78
8
SparseArray[list]["NonzeroValues"]

Should perform quite well on large lists...

ciao
  • 25,774
  • 2
  • 58
  • 139