# Having Mathematica automatically plug in the values for a system of equations

I have a set of pairs, such as {{8 a, 2 + 2 a}, {8 b, 1 + 3 a}}. This set encodes the fact that I want to put 8a == 2+2a and 8b == 1+3b. I can manually type

Solve[8a==2+2a&&8b==1+3a]


to figure out that a -> 1/3 and b -> 1/4 are the solutions of this system, and then type

a = 1/3; b = 1/4;


to set the variables to their actual values. However, I'd like to have Mathematica set a=1/3 and b=1/4 for me, to use in later computations. In the actual example I'm working with, the number of variables is much larger, but the equations are still all linear and have a unique solution. Thus, it is tiresome to go through each variable one-by-one and plug in its value.

The code below accomplishes what you asked. However, note that once a and b have been assigned values they can no longer be used as unknowns for further work. An alternative is to assign values to another symbol set, or to simply preserve a list of solutions for use when all equations have been solved.

expr = {{8 a, 2 + 2 a}, {8 b, 1 + 3 a}};

makeEquations[lst_] :=
lst /. {{t1_, t2_}, {t3_, t4_}} -> t1 == t2 && t3 == t4

makeEquations[expr]

(* 8 a\[Equal]2+2 a&&8 b\[Equal]1+3 a *)

sol = Solve[makeEquations[expr], {a, b}][]

(*  {a -> 1/3, b -> 1/4} *)

{a, b} = {a, b} /. sol

• @PaceNielsen. Yeah, I mean, I would leave a and b undefined and just use the replacement rules generated from Solve. This is idiomatic in Mathematica. – march Feb 14 '19 at 20:25
• To convert the lists into equations, Apply Equal to level 1 of the lists. eqns = Equal @@@ lists – Bob Hanlon Feb 14 '19 at 20:42
• This helped me cobble together code that does what I need. Special thanks to march and Bob Hanlon! – Pace Nielsen Feb 14 '19 at 21:04

Replace rules by variable setters:

Solve[8 a == 2 + 2 a && 8 b == 1 + 3 a] /. Rule -> Set


After this, the variables are set to $$a=\frac13$$ and $$b=\frac14$$.

This trick assumes that there's only one set of solutions.