1
$\begingroup$


I want to solve equations and substitute one of the variable with the answer.
For example, here I have two variables (x, y) and two constants (a, b) ranging from 1~10, use FindRoot to solve them. I want to output only the x solution and replace it with the variable "x".

Do[sol = FindRoot[{a x + b y == 0, a x - b y == 4}, {x, 0}, {y, 0}], x = x /. sol[[1]], {a, 1, 10}, {b, 1, 10}]

But there must be something wrong. How can I solve it?
Thanks~

$\endgroup$
0

1 Answer 1

3
$\begingroup$

I want to output only the x solution and replace it with the variable "x".

I am not sure what you mean by this. Do you want only the x solutions in list as numbers and assign this list to x? or something else?

Clear["Global`*"]
root[a_Integer, b_Integer, x_Symbol, y_Symbol] := 
 FindRoot[{a x + b y == 0, a x - b y == 4}, {x, 0}, {y, 0}]

data = Flatten[Table[root[a, b, x, y], {a, 1, 10}, {b, 1, 10}], 1];
data /. {x -> any1_, y -> any2_} :> x -> any1

The above gives

Mathematica graphics

If you just want list of the x values assigned to x variable (btw, I think it is better to assign this to new variable name and not x. Something like xSol. So this below becomes xSol = x /. data but if you want to use x as variable then

x = x /. data

and now x variable is

Mathematica graphics

And if you want only unique values in x you can do

x = Union[x]

Mathematica graphics

Other variations are possible.

$\endgroup$
1
  • $\begingroup$ Wow~thanks, this is helpful. $\endgroup$
    – 林怡君
    Dec 28, 2021 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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