Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace expressions with their names in Mathematica

I have some expressions in Mathematica that are defined in terms of other expressions. I want to take some functions of the larger expression and then get the result in terms of the subexpressions. Example:

In[78]:= e1 = x + y;
e2 = 2^e1;

In[80]:= D[e2, x]

Out[80]= 2^(x + y) Log[2]

I want the output to instead be 2^e1 Log[2]. I am currently using ReplaceAll as follows, but this is cumbersome in my actual application with about 20 subexpressions.

In[81]:= D[e2, x] /. e1 -> E1

Out[81]= 2^E1 Log[2]
like image 914
brentonk Avatar asked Feb 25 '23 05:02

brentonk


2 Answers

Difficult to obtain and keep that form, if you set e1 to be x+y. So if you do not really need that, could instead work with replacement rules.

rul = {e1->x+y, e2->2^e1};
revrul = {x+y->e1};

InputForm[D[e2//.rul, x] /. revrul]

Out[5]//InputForm= 2^e1*Log[2]

Daniel Lichtblau Wolfram Research

like image 199
Daniel Lichtblau Avatar answered Feb 27 '23 17:02

Daniel Lichtblau


Your answer appears to be specific due to the simple form of your e1 and e2. One possibility is to define e2 as a function in terms of e1, without specifying what e1 is:

In[8]:= Clear[e1, e2];
e2[x_] := 2^e1[x]

Then

In[10]:= D[e2[x], x]

Out[10]= 2^e1[x] Log[2] Derivative[1][e1][x]

which is a generally correct answer. As soon as you want it to compute, you can provide specific definition for e1. You can also do this inside Block, so that you don't introduce global definitions:

In[11]:= 
Block[{e1},
  e1[x_] := x + y;
  D[e2[x], x]]

Out[11]= 2^(x + y) Log[2]

I suppose this approach can scale to a larger number of sub-expressions.

HTH

like image 20
Leonid Shifrin Avatar answered Feb 27 '23 18:02

Leonid Shifrin