# How to get a number from Solve [duplicate]

It's often useful to get just one number from Solve. I use the following construction for acquiring one solution from the expression returned by Solve.

q = t /. Solve[p == 2 t + 1, t][[1]]


Mostly I don't like to use the different variable name within Solve. And the rule-applying seems very unnatural. I think a solution that is more elegant must exist. Can anyone show me this?

-

## marked as duplicate by Artes, b.gatessucks, m_goldberg, Yves Klett, Michael E2Mar 9 '14 at 18:12

Solve[p == 2 t + 1, t][[1, 1, 2]] ? –  b.gatessucks Mar 9 '14 at 11:04
Wow, thank you, I'll serch for what does it mean... –  Himura Mar 9 '14 at 11:06
Since you ask for the first solution you should use e.g. s[[1, 1, 2]] instead of s[[All, 1, 2]] etc. However you should remember that more flexible way is using ReplaceAll, e.g. here t /. First @ Solve[..., t]. –  Artes Mar 9 '14 at 11:18
I feel closing this is fine, but I am glad I had the opportunity to post an answer. –  Jacob Akkerboom Mar 9 '14 at 13:00

Just extract second argument from Rule function by

Solve[p == 2 t + 1, t][[1, All, 2]]


Use All in case of more then one solution.

-
Thank you. Now it's a bit better. But the problem of the variable names is still exist –  Himura Mar 9 '14 at 11:12

I am not sure what exactly you mean by "the problem of the variable names" (in the comments). Anyway you could construct a function like this (ignore the red syntax highlighting in the definition)

SyntaxInformation[solveAndAssign] = {"LocalVariables" -> {"Solve", {2, 2}}};
SetAttributes[solveAndAssign, HoldAll];
solveAndAssign[eqn_, var_Symbol] :=
(
var =
Block[{var},
var /.
First[
Solve[
eqn
,
var
]
]
]
)


Example

q = 3;
solveAndAssign[p == 2 q + 1, q];
q


Outputs

1/2 (-1+p)

In the example above you see that you can use the variable you want to assign to in your equation. The code still works if you put your equation in a variable (the attribute HoldAll might make you think otherwise). Of course the equation has to formulated in terms of q rather than the value of q, which is why we Clear q for the moment.

Clear@q
eqn = p == 2 q + 1;
q = 3;
solveAndAssign[eqn, q];
q


Outputs

1/2 (-1+p)