Re: logical indexing using more than one variable in a pure function
- To: mathgroup at smc.vnet.net
 - Subject: [mg53357] Re: [mg53342] logical indexing using more than one variable in a pure function
 - From: "David Park" <djmp at earthlink.net>
 - Date: Sat, 8 Jan 2005 02:39:24 -0500 (EST)
 - Sender: owner-wri-mathgroup at wolfram.com
 
Ben,
If one wants to perform operations on two equal length lists, then Inner is
a convenient command.
x = {2, 3, 4, 5, 6};
y = {True, False, False, True, True};
x1 = {6, 5, 4, 3, 2};
Inner[If[#2, #1, Unevaluated[Sequence[]]] &, x, y, List]
{2, 5, 6}
Inner[If[#1 > #2, #1, Unevaluated[Sequence[]]] &, x, x1, List]
{5, 6}
For three or more equal length lists we can use...
MapThread[If[2*#2 > #1 && #3, #1,
    Unevaluated[Sequence[]]] & , {x, x1, y}]
{2, 5}
David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/
From: Ben Barrowes [mailto:barrowes at alum.mit.edu]
To: mathgroup at smc.vnet.net
I am trying to pick out values from a matrix using a logical mask, i.e.
using logical indexing.
I wish the following:
x = {2, 3, 4, 5, 6}
y = {True, False, False, True, True}
x[[y]]
would produce:
{2,5,6}
but instead it produces:
\!\(\*
   RowBox[{\(Part::"pspec"\), \(\(:\)\(\ \)\), "\<\"Part specification \
\\!\\({True, False, False, True, True}\\) is neither an integer nor a
list of \
integers. \\!\\(\\*ButtonBox[\\\"More\[Ellipsis]\\\", \
ButtonStyle->\\\"RefGuideLinkText\\\", ButtonFrame->None, \
ButtonData:>\\\"General::pspec\\\"]\\)\"\>"}]\)
{2, 3, 4, 5, 6}\[LeftDoubleBracket]{True, False, False, True,
     True}\[RightDoubleBracket]
Here are some working examples when the mask depends upon only one variable:
pick out values in x > 4
Select[x, (#1 > 4 &)]
{5, 6}
BooleanSelect seems to do what I want if I have a logical mask already:
<< Statistics`DataManipulation`
BooleanSelect[x, y]
{2, 5, 6}
And now in 5.1, "Pick" does the same thing as BooleanSelect.
But how can I do this in one line? (no need to define y explicitly)
Something like:
Pick[x,x>3]
This seems to work for cases:
Cases[x, x_ /; x > 3]
{4, 5, 6}
and similarly for select:
Select[x, # > 3 &]
{4, 5, 6}
But if I have a second List:
x1 = {6, 5, 4, 3, 2}
How would I index x based on a logical operation on both x and x1?
I hoped something like this would work:
Pick[x,x>x1]
or
Cases[x, {x_,x1_} /; x>x1]
{}
But only x is provided to the pattern match, not {x_,x1_}.
Or maybe a better Select statement. But how do I make the pure function
accept two arguments?
For that matter, how can I perform an element by element logical
operation on a list? For example, I would like:
x>3
to return
{False,False,True,True,True}
instead of
{2, 3, 4, 5, 6} > 3
and
x>x1
to return
{False,False,False,True,True}
instead of
{2, 3, 4, 5, 6} > {6, 5, 4, 3, 2}
will something like:
#1 > #2 &, x, x1
work?
I would appreciate any suggestions,
Ben