Re: MapThread and If
- To: mathgroup at smc.vnet.net
- Subject: [mg68026] Re: MapThread and If
- From: albert <awnl at arcor.de>
- Date: Fri, 21 Jul 2006 05:37:11 -0400 (EDT)
- References: <e9nkro$9u3$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Arkadiusz Majka wrote:
> Hi,
>
> Of course
>
> MapThread[If[#1 == #2, 0, tr] &, {{1, 2, 3}, {2, 2, 4}}]
>
> I get
>
> {tr, 0, tr}
>
> and for
>
> MapThread[If[#1 == #2, 0, tr] &, {{1, 2, 3}, {2, 2, {3, 4}}}]
>
> I get
>
> {tr, 0, If[3 == {3, 4}, 0, tr]}
>
> How I can build in above MapThread expression information that if 'a'
> is equal to any element from the list {a,b,c,d} the result is 0. In
> above example we have If[3=={3,4},0,tr] what I want to be 0, because 3
> is equal to an element belonging to {3,4}.
>
This should do what you want:
MapThread[Function[{x,y},If[MemberQ[Flatten[{y}],x],0,tr],HoldAll],{{1, 2,
3}, {2, 2, {3, 4}}}]
There might be shorter versions, but this shows what you have to take care
off: you need to prevent the condition to be evaluated before the function
is applied to the actual data. For #1==#2 this is "automatically" because
Equal is not evaluated in this case. When using MemberQ or any other
function this is typically not the case. This is why I needed to use the
more elaborate version of the function definition. Of course you could also
use an explicit named function:
repfun[a_,b_]:= If[MemberQ[Flatten[{b}],a],0,tr]
MapThread[repfun,{{1, 2, 3}, {2, 2, {3, 4}}}]
which would probably be a lot easier to read...
hth
albert