1
$\begingroup$

Assume the call to the routine Solve[eqn==0,{x1,x2}] returns:

{{x1->a1,x2->a2},{x1->b1,x2->b2}}

I would like to from the solutions matrix

{{a1,a2},{b1,b2}}

with a nice way.

$\endgroup$
  • 2
    $\begingroup$ See this documentation article. (In your case, you could use {x1,x2} /. solution) $\endgroup$ – Lukas Lang Oct 30 at 9:00
  • $\begingroup$ Consider also {{x1->a1,x2->a2},{x1->b1,x2->b2}}/.Rule[_,val_]->val $\endgroup$ – MaPo Oct 30 at 9:19
  • 1
    $\begingroup$ Or Values /@ solution. $\endgroup$ – C. E. Oct 30 at 9:27
  • 2
    $\begingroup$ .. or just Values@solution $\endgroup$ – kglr Oct 30 at 9:31
3
$\begingroup$

Easiest way to get the right-hand-sides of a (arbitrarily nested) list of Rules is to use Values:

rules = {a -> 1, {b -> 2, {c -> 3, a -> 4}}};
Values @ rules

{1, {2, {3, 4}}}

For the list of rules returned by Solve:

solution = {{x1 -> a1, x2 -> a2}, {x1 -> b1, x2 -> b2}};
Values @ solution

{{a1, a2}, {b1, b2}}

solution2 = Solve[y - x == a && x - y^2 == b, {x, y}]

{{x -> 1/2 (1 - 2 a - Sqrt[1 - 4 a - 4 b]), y -> 1/2 (1 - Sqrt[1 - 4 a - 4 b])},
{x -> 1/2 (1 - 2 a + Sqrt[1 - 4 a - 4 b]), y -> 1/2 (1 + Sqrt[1 - 4 a - 4 b])}}

Values @ solution2

{{1/2 (1 - 2 a - Sqrt[1 - 4 a - 4 b]), 1/2 (1 - Sqrt[1 - 4 a - 4 b])},
{1/ 2 (1 - 2 a + Sqrt[1 - 4 a - 4 b]), 1/2 (1 + Sqrt[1 - 4 a - 4 b])}}

Alternatively, define a function that returns the solution values directly (similar to DSolveValue):

ClearAll[solveValue]
solveValue = Values @* Solve;

solveValue[y - x == a && x - y^2 == b, {x, y}]

{{1/2 (1 - 2 a - Sqrt[1 - 4 a - 4 b]), 1/2 (1 - Sqrt[1 - 4 a - 4 b])},
{1/ 2 (1 - 2 a + Sqrt[1 - 4 a - 4 b]), 1/2 (1 + Sqrt[1 - 4 a - 4 b])}}

$\endgroup$
1
$\begingroup$

Check also the following. Let

sol = {{x1 -> a1, x2 -> a2}, {x1 -> b1, x2 -> b2}}

be your solution. Then try this:

sol /. {x_ -> a_, y_ -> b_} -> {a, b}

(* {{a1, a2}, {b1, b2}}  *)

Have fun!

$\endgroup$

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