Re: "a[A_,B_] :=" Does not assign variables properly. Why?
- To: mathgroup at smc.vnet.net
- Subject: [mg36158] Re: [mg36141] "a[A_,B_] :=" Does not assign variables properly. Why?
- From: Omega Consulting <omega_consulting at yahoo.com>
- Date: Fri, 23 Aug 2002 21:34:49 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
At 11:25 PM 8/22/2002, Jason Welter wrote: >Here's a piece of a conversion I had with Mathematica. >Why is "a[A_,B_] := LinearSolve[X,Y][[1]]" not giving >me the function I expect? > >In[261]:= X = {{0,0,0,1},{1,0,0,1},{0,1,0,1},{1,1,1,1}}; >In[262]:= Y = {A,B,C,D}; >In[263]:= LinearSolve[X,Y] >Out[263]= {-A+B,-A+C,A-B-C+D,A} >In[264]:= LinearSolve[X,Y][[1]] >Out[264]= -A+B >In[265]:= a[A_,B_] := LinearSolve[X,Y][[1]] >In[266]:= a[1,3] >Out[266]= -A+B > >The output above is not what I want. I want "2". Here's >what I expect: > >In[267]:= a[A_,B_] := -A+B; >In[268]:= a[1,3] >Out[268]= 2 > >This output is what I expect. What is the difference between >the two? This is a common misconception about what := does. What it does is set up a variable replacement for the unevaluated expression, not the evaluated expression. So a[A_,B_] := LinearSolve[X,Y][[1]] a[1,3] is similar to doing ReleaseHold[ Hold[ LinearSolve[X,Y][[1]] ] /. {A->1, B->3} ] which means that only explicit instances of A and B are replaced. What you are attempting is done with =. This assigns the function to the evaluated expression. In[5]:=a[A_,B_] = LinearSolve[X,Y][[1]] Out[5]=-A+B In[6]:=a[1,3] Out[6]=2 There are certain situations where you get a different result if you evaluate with the values or replace the values in the symbolic evaluation. (This example is not one of them.) Using = does the later. If you want to do the former, you should use := and have the right hand side use A and B explicitly or you could use a Block. In[7]:=a[b_,c_] := Block[{A=b, B=c}, LinearSolve[X,Y][[1]] ] In[8]:=a[1,3] Out[8]=2 -------------------------------------------------------------- Omega Consulting "The final answer to your Mathematica needs" Spend less time searching and more time finding. http://www.wz.com/internet/Mathematica.html