Search code examples
wolfram-mathematicavariable-assignmentdifferential-equations

Is there a method to put a expression into a variable in Mathematica, without concern of local variables?


I'm using NDSolve in Mathematica to solve a set of equations. I'm looking for some way to put the set of equations in to a variable and refer to it latter in NDSolve to make the code more easy to read.

Here is a simpler version of what I'm doing:

In[1]:= equs = {a x + b y == 0, x - y == 1};
In[2]:= f[a_, b_] := Module[{x, y}, {x, y} /. Solve[equs, {x, y}]]

When evaluate it doesn't give the right answer:

In[3]:=   f[1, 1]
Out[3]:=  {x$627, y$627}

This is because x,y,a,b are local variables, they are given internal names different from x,y,a,b. If I change the definition of equs into a function, it can give right result:

In[4]:= Clear[equs, f]

In[5]:= equs[x_, y_, a_, b_] := {a x + b y == 0, x - y == 1};

In[6]:= f[a_, b_] := 
 Module[{x, y}, {x, y} /. Solve[equs[x, y, a, b], {x, y}]]

In[7]:= f[1, 1]

Out[7]= {{1/2, -(1/2)}}

But my problem is I have more then 20 variables in equs in my real code, and to write them out explicitly will make the code not easy to read. Is there any way to solve this?


Solution

  • This variation seems to work for me:

    equs = {a x + b y == 0, x - y == 1};
    sols = Block[{x, y}, {x, y} /. (Solve[equs, {x, y}])];
    f[a_, b_] := Evaluate[sols];
    f[1,1]
    

    I'm not sure what your real system looks like, but maybe something like this would work.