1
$\begingroup$

suppose I have a long list of many variables: alist = { u, v, w, ... }. At some point, I have another combination of variables depending on { u, v, w, etc.},e.g., alpha = 2 * u + v beta = v + w^2. And now I want to substitute u, v, and w with the following expressions: u = 3 - x + y; v = Exp[y] + z; etc., where the right hand side ( say 3 - x + y ) is contained in another list of expressions, say blist[[1]] = 3 - x + y.

For the task stated above, I naively input alist[[i]] = blist[[i]], but obviously this will do the job. what it merely does is to assign 3 - x + y to alist[[1]] ( when i == 1 ).

I want to know if it is possible to treat alist[[1]] = 3 - x + y as a pattern rule: u = 3 - x + y rather than assign 3 - x + y to alist. Thank you !

array = {u, v, w}

Out[362]= {a, b, c}

alpha = 2 * u + v

array[[1]] = 2 x + y

In[367]:= u

u (* meant to be 2 u + y *)

In[368]:= alpha

alpha (* meant to be  4 x + 2 y + v *)

```
$\endgroup$
1
  • 1
    $\begingroup$ I think you want to use Rule. $\endgroup$
    – Alan
    Jul 16, 2020 at 11:48

2 Answers 2

1
$\begingroup$

As pointed out in the comments by Alan, Rule and ReplaceAll is what you need.

An example

ReplaceAll[{Rule[u, x + y], Rule[v, x - y]}][u + v]
(* 2 x *)

which can be written more succinctly as

u + v /. {u -> x + y, v -> x - y}
(* 2 x *)

In the case that you have your alist and blist, a list of rules can be created as follows

alist = {u, v};
blist = {x + y, x - y};
rules = Thread[Rule[alist, blist]]
(* {u -> x + y, v -> x - y} *)

If you have an expression expr in terms of "a" variables, you can then replace them via

expr /. rules
$\endgroup$
1
$\begingroup$

I had some trouble understanding your question, but I think the following can be adapted to do what you want.

left = {u, v, w}
right = {3 - x + y, Exp[y] + z, etc}
rules = Thread[Rule[left, right]]
alpha = 2*u + v
beta = v + w^2
alpha /. rules
beta /. rules
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.