3
$\begingroup$

I am new to Mathematica and I am working on a code on which the final output depends on variables evaluated from the inputs A simplified example: (x,y) inputs ,(q,w) intermediate values, (z) output

x = Input["x"]
y = Input["y"]
q = 2 x
w = 3 y
z = 4 q + 5 w
f = 3 x + 4 y

This works just fine, but I want to manipulate the inputs so i tried

q = 2 x
w = 3 y
Manipulate[z = 4 q + 5 w, {x, 0, 10}, {y, 0, 10}]

the result for z is 8x+15y that doesn't change with moving x and y sliders.. so i tried

Manipulate[q = 2 x, {x, 0, 10}]
Manipulate[w = 3 y, {y, 0, 10}]
z = 4 q + 5 w
f = 3 x + 4 y

which worked for z but did not work for f as apparently the values of x and y aren't stored my questions are
1- how to set the values for x and y from manipulate ?
2- the value of z isn't evaluated when i move the sliders but i have to run the code again and the sliders are thus reset. How can i get the result of z instantaneously by moving the sliders of x and y. Thanks alot.

$\endgroup$
2
$\begingroup$

Another approach slightly different from LLIAMnYP's answer to is to go ahead and treat the x and y variables as local to Manipulate. In this approach x and y are updated dynamically and used to compute the intermediate results, q and w.

x and y are used to directly compute f but the intermediate results are used to compute z.

One uses DyanmicModule to localize q, w, f and z.

Manipulate[

 DynamicModule[
  {
   q = 2 x,
   w = 3 y,
   f,
   z
   },

  f = 3 x + 4 y;
  z = 4 q + 5 w;

  Row[{"f = ", f, "  z = ", z}]
  ], (* end of DynamicModule *)

 {{x, 1}, -10, 10, Appearance -> "Open"},
 {{y, 2}, -10, 10, Appearance -> "Open"}
 ]

Row is used to display the results. Below is what it looks like for the initial settings x=1 and y=2.

Mathematica graphics

$\endgroup$
2
$\begingroup$

The problem here is scoping. x and y inside the Manipulate are not the same x and y that you use globally. In order to remedy this, use the option LocalizeVariables -> False.

Manipulate[{q = 2 x, w = 3 y}, {x, 0, 10}, {y, 0, 10}, LocalizeVariables -> False]
(* slide around *)
x
(* 3.74 *)
z = 4 q + 5 w
f = 3 x + 4 y
(* 103.72 *)
(* 30.9 *)

Perhaps a further improvement, try

Dynamic[z = 4 q + 5 w]
Dynamic[f = 3 x + 4 y]

and watch the values of f and z be updated on-the-fly.

$\endgroup$

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.