Listable attribute (was Re: eval differential expressions)
- To: mathgroup at yoda.physics.unc.edu
- Subject: Listable attribute (was Re: eval differential expressions)
- From: lewin at ipgp.jussieu.fr (Eric LEWIN - IPGP Geochimie)
- Date: Mon, 20 Jun 1994 12:01:26 +0100
>From the question of Geoff Latham <gal at melba.bby.com.au>: >Is there an easy way to evaluate differential expressions for various >functions? >For example, if I have D[f[x],x]^2+f[x] in Mma, I'd like to evaluate it for >various functions f[x]. This can be done via naming the expression and >then letting f[x_]=<desired fn of x> and typing the expressions name >upon which its evaluated - but this seems awfully clumbsy! Here is just one solution, using the listability, which ends with another question: In[1]:= Diff[fun_,var_] := D[fun,var]^2 + fun In[2]:= Diff[ { Cos[x], Sin[x], Tan[x] }, x ] 2 2 4 Out[2]= {Cos[x] + Sin[x] , Cos[x] + Sin[x], Sec[x] + Tan[x]} Et voila, it can probably do what Geoff asked. But at my first try, I thought at the Listable attribute, but I have discovered that since the Plus[], D[] and Power[] have it, it is useless. In fact, it is not useless, it is worse than that: In[3]:= Diff[ Exp[x+y^2], {x, y}] 2 2 x + y x + y 2 Out[3]= E + D[E , {x, y}] In[4]:= SetAttributes[Diff, Listable] In[5]:= Diff[ Exp[x+y^2], {x, y}] 2 2 2 2 x + y 2 x + 2 y x + y 2 x + 2 y 2 Out[5]= {E + E , E + 4 E y } At that point, the "listability" seems extended to the second argument, which can be nice. Alas, one can not pull the line too much: In[6]:= Diff[{1,x,x y},{x,y}] Thread::tdlen: Objects of unequal length in Diff[{1, x, x y}, {x, y}] cannot be combined. 2 (y,0) 2 Out[6]= {1, x + D[x, {x, y}] , x y + Times [x, y] } Thus my question: does somebody know how to limit the Listable attribute to one of the arguments (a kind of "ListableOnFirstArg" attribute), or does one have to explicit rules with Thread and so on ? Finally, coming back to the beginnning, the original Geoff Latham's problem can also be solved by other means. That would be interesting to see here as many different solutions as we can imagine. The most obscure one (the shortest ?) I can think of is: In[7]:= {1, x, x^2} // (D[#,x]^2 + #)& 2 Out[7]= {1, 1 + x, 5 x } Happy Mmathing - ELw =====[ Eric LEWIN - lewin at ipgp.jussieu.fr - IPGP Geochimie ]===== = Labo de Geochimie et Cosmochimie / Institut de Physique du Globe = ========================== Paris - FRANCE ==========================