2
$\begingroup$
Clear[x, y];
function2[eqn3_, eqn4_] := 
 Module[{x, y, sol}, sol = Solve[{eqn3, eqn4}, {x, y}]; {x, y} /. sol]
function2[y == 3 x, y == x^2 - 4]

I want it to solve for x and y but this wouldnt work. I am not quite sure about how to use Solve in a Module

$\endgroup$
0

1 Answer 1

2
$\begingroup$

It is best to pass the variables to the function

function2[eqn3_, eqn4_, x_, y_] := Module[{sol},
  sol = Solve[{eqn3, eqn4}, {x, y}];
  {x, y} /. sol
  ]
function2[y == 3 x, y == x^2 - 4, x, y]

Gives

{{-1, -3}, {4, 12}}

Otherwise, different context.

When you did this

function2[eqn3_, eqn4_] := Module[{x, y, sol},
  sol = Solve[{eqn3, eqn4}, {x, y}];
  {x, y} /. sol
  ]
function2[y == 3 x, y == x^2 - 4]

Then the x,y in the equations are global context, but then you defined local x,y inside the module, which are different context (even though they look the same on the screen), they are different symbols under the cover.

$\endgroup$
2
  • 1
    $\begingroup$ You were just a few seconds faster ;-). I propose something like systemSolver[system_List, vars_List] := Module[{sol}, sol = Solve[system, vars]; vars /. sol ] its more flexible like the OP version, but her is only duplicates Solve ;-) $\endgroup$
    – mgamer
    Mar 26, 2020 at 7:45
  • $\begingroup$ This is a common problem in more general settings. Is there a general post on this issue? I think there are two problems: 1) having to input the variables and 2) having to output the solution if it contains variables. For outputting the solution one may use pure functions. See here $\endgroup$
    – Hugh
    Mar 26, 2020 at 10:07

Your Answer

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

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