Assign the results from a Solve to variable(s)
Usually you don't want to actually assign values to x
and y
, and you would use replacement rules instead:
sols = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}];
{x, y} /. sols[[1]]
or for the second solution:
{x, y} /. sols[[2]]
If you really want to assign values to x
and y
globally, you could use:
Set @@@ sols[[1]]
but you must clear x
and y
before using another set:
Clear[x, y]
Set @@@ sols[[2]]
If you want to assign values to x
and y
within a Block
you could do something like this:
Hold @@ {sols[[2]]} /. Rule -> Set /. _[vars_] :>
Block[vars,
Sin[x] + Sqrt[y] // N
]
This uses what I am calling the injector pattern to get the values into Block
in the right syntax without it prematurely evaluating.
Related questions:
Getting rid of the “x ->” in FindInstance results
Using the output of Solve
You can do this :
s = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}];
xx = s[[All, 1, 2]];
yy = s[[All, 2, 2]];
Now you can access solutions, this way xx[[1]]
, yy[[2]]
.
If you prefer to collect solutions in Array
, there is another way :
X = Array[ x, {Length@s}];
Y = Array[ y, {Length@s}];
x[k_] /; MemberQ[ Range[ Length @ s], k] := s[[k, 1, 2]]
y[k_] /; MemberQ[ Range[ Length @ s], k] := s[[k, 2, 2]]
now X
is equivalent to s[[All, 1, 2]]
, while Y
to s[[All, 2, 2]]
, e.g. :
X[[1]] == x[1]
Y == s[[All, 2, 2]]
True True
You do not have to use or even to define X
and Y
arrays,
e.g.
{x[1], y[1]}
{(-11181 - Sqrt[2242057])/74498, 1/386 (13 - Sqrt[2242057])}
We've used Condition
i.e. /;
to assure definitions of x[i], y[i]
only for i
in an appropriate range determined by Length @ s
, i.e. number of solutions.
Update: Version 10 built-in function Values does value extraction conveniently for rules appearing in lists of arbitrary lengths and depths:
{{x1, y1}, {x2, y2}} = Values[Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]]
(* {{(-11181-Sqrt[2242057])/74498,1/386 (13-Sqrt[2242057])},
{(-11181+Sqrt[2242057])/74498,1/386 (13+Sqrt[2242057])}} *)
Another example:
lst={{a->1,b->2},{c->3},{{d->4}},{e->5,{f->6,{g->7}}}};
Values[lst]
(* {{1,2},{3},{{4}},{5,{6,{7}}}} *)
Original post:
{{x1, y1}, {x2, y2}} = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}][[All, All, -1]]
(* {{(-11181 - Sqrt[2242057])/74498, 1/386 (13 - Sqrt[2242057])},
{(-11181 + Sqrt[2242057])/74498, 1/386 (13 + Sqrt[2242057])}} *)
{x1, y2}
(* {(-11181- Sqrt[2242057]) / 74498, 1 / 386 (13 + Sqrt[2242057])} *)