MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Threading over matrices


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


  • Prev by Date: Running programs from the command line in Mathematica
  • Next by Date: Sending Objects from Java - Mathematica
  • Previous by thread: Re: Threading over matrices
  • Next by thread: Re: Threading over matrices