2
$\begingroup$

I have a nested array for example:

myVals = {{1, 2, 3, 4, 5, 6}, {20, 20, 21, 3, 15, 7}, {2, 3, 35, 106}};

And suppose I want to select in each sub-array, all elements not equal to 3, then:

Select[#, # != 3 &] & /@ myVals
{{1, 2, 4, 5, 6}, {20, 20, 21, 15, 7}, {2, 35, 106}}

seems to work but I think it's awkward as the place holders # actually represent two different items: The first # is a sub-array like {1,2,3,4,5,6}, and the second one represents each item in that sub-array.

Is this a standard way of doing this in a one-line command? I'm running 12.3.

$\endgroup$
5
  • 2
    $\begingroup$ try DeleteCases[myVals, 3, 2] and Cases[#, Except[3]] & /@ myVals? $\endgroup$
    – kglr
    Sep 23 at 18:17
  • 1
    $\begingroup$ if you have to use Select, try Select[#, x|-> ! x == 3] & /@ myVals $\endgroup$
    – kglr
    Sep 23 at 18:23
  • $\begingroup$ @kglr: Noticed if I have real vals in array and use Abs[x], DeleteCases won't work: myVals = {{1, 2, 3, 4, 5, 6, 0.001}, {20, 20, 21, 3, 15, 7, 0.00001}, {2, 3, 35, 106, 0.001}}; DeleteCases[myVals, Abs[#] < 0.0001 &, 2] But the Select syntax you posted does work. Thanks! $\endgroup$
    – josh
    Sep 23 at 18:49
  • $\begingroup$ josh, the second argument in DeleteCases (and in Cases) should be a pattern. That is, you should use something like DeleteCases[myVals, x_ /; Abs[x] < 0.0001, 2]. $\endgroup$
    – kglr
    Sep 23 at 19:06
  • $\begingroup$ kglr, thanks for the info about using patterns. That works nice and is simple to understand for me. $\endgroup$
    – josh
    Sep 23 at 19:32
3
$\begingroup$

Perhaps this is clearer

Select[#, Function[x, x != 3]] & /@ myVals
$\endgroup$
1
  • $\begingroup$ That works nice Chris and also works in my case where I'm removing real numbers such as: Select[#, Function[x, Abs[x] > 0.01]] & /@ myVals $\endgroup$
    – josh
    Sep 23 at 19:34
3
$\begingroup$
Clear["Global`*"]

myVals = {{1, 2, 3, 4, 5, 6}, {20, 20, 21, 3, 15, 7}, {2, 3, 35, 106}};

Use the operator form of Select

Select[# != 3 &] /@ myVals

(* {{1, 2, 4, 5, 6}, {20, 20, 21, 15, 7}, {2, 35, 106}} *)
$\endgroup$
3
$\begingroup$

Another variation with Select that avoids using any hashes:

Select[UnequalTo[3]] /@ myVals

{{1, 2, 4, 5, 6}, {20, 20, 21, 15, 7}, {2, 35, 106}}

And a variation with DeleteCases that also avoids using hashes:

DeleteCases[3] /@ myVals

{{1, 2, 4, 5, 6}, {20, 20, 21, 15, 7}, {2, 35, 106}}

$\endgroup$
2
$\begingroup$
DeleteCases[#, 3] & /@ myVals

OR:

myVals /. 3 -> Nothing

OR:

Select[#, x |-> x != 3] & /@ myVals
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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