0
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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}][[1]]

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

{a, b} = {a, b} /. sol
$\endgroup$
  • 2
    $\begingroup$ @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. $\endgroup$ – march Feb 14 at 20:25
  • 2
    $\begingroup$ To convert the lists into equations, Apply Equal to level 1 of the lists. eqns = Equal @@@ lists $\endgroup$ – Bob Hanlon Feb 14 at 20:42
  • $\begingroup$ This helped me cobble together code that does what I need. Special thanks to march and Bob Hanlon! $\endgroup$ – Pace Nielsen Feb 14 at 21:04
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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