0
$\begingroup$

Suppose I want to solve a simple equation in mathematica x-a=0.So I am writing the mathematica code for this as below:

Solve[x - a == 0, x]

So the output will be as below:

{{x -> a}}

Now suppose I have assigned a value for 'a' beforehand and then want to solve the same equation.So my code will look like below:

a = 1;
Solve[x - a == 0, x]

And the output in this case will be like below:

{{x -> 1}}

Now if I want an output in this case as {{x -> a}},what modification should I do in my code ?

Note: Clear[a] will work,but I don't want to remove permanently the assigned value to a

$\endgroup$
4
  • 2
    $\begingroup$ Clear[a] before solving? $\endgroup$
    – Roman
    Feb 22 '21 at 8:09
  • $\begingroup$ Yeah it will work,but I don't want to remove the assigned value $\endgroup$ Feb 22 '21 at 8:10
  • 1
    $\begingroup$ What about sol[a_] := Solve[x - a == 0, x][[1]] $\endgroup$ Feb 22 '21 at 8:40
  • 1
    $\begingroup$ Depending on your use case, a = 1; Block[{a = Defer[a]}, Solve[x - a == 0, x]] might help. $\endgroup$
    – MarcoB
    Feb 22 '21 at 14:07
2
$\begingroup$

I'm sure there is a better way for your solution but as far as I know:

You can use Context to manage variable scopes:

When you want to use a variable like a, Mathematica define it globally, what you can do is to do it in a context:

Begin["MyContext1`"];

a = 2;

Solve[x - a == 0, {x}]

End[];

(*Out: {{x -> 2}} *)

Now you want to use a again as a new variable without losing the previous value, use another context:

Begin["MyContext2`"];

Solve[x - a == 0, {x}]

End[];

(* {{x -> a}} *)

You can access the previous value by beginning the context you'd defined:

Begin["MyContext1`"];

a

End[];

(*Out: 2 *)

Remember if you use a without starting a context (use it globally), this solution will not work and also don't forget to end the context.

$\endgroup$
1
  • $\begingroup$ thanks @Beny Izd $\endgroup$ Feb 22 '21 at 18:15

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.