Re: Threading over matrices
- To: mathgroup at smc.vnet.net
- Subject: [mg90753] Re: Threading over matrices
- From: yatesd at mac.com
- Date: Wed, 23 Jul 2008 05:56:35 -0400 (EDT)
- References: <g64487$djo$1@smc.vnet.net>
The reason that Cos, Sin etc work is because they have Attribute
Listable. (You can see this by typing Attributes[Cos], etc.) Your own
custom functions, by default, do not. (Nor does Greater (>) which
explains why x>y etc do not work). There are at least two relatively
easy ways to create a function with Attribute Listable.
(1)
Clear[f];
SetAttributes[f,Listable];
f[x_,y_]:=If[x>y,1/x,x-y]
(2) Use a pure function.
Function[{x,y},If[x>y,1/x,x-y],{Listable}][x,y]
or when you don't know how many arguments will be passed
Function[Null, Greater[##],{Listable}][x,y]
or if you need to reuse the function you can do
f= Function[Null, Greater[##],{Listable}];
f[x,y]
(The trick of using Null as the first argument in Function in order to
use # (or #2 or ## as required) in the definition, followed by the
list of Attributes is not documented anywhere that I could find, but
is a very useful trick.)
Regards,
Derek