TransWikia.com

Accommodating local variables within Dynamic

Mathematica Asked by Russ Lyons on April 6, 2021

I would like to use a local variable within Dynamic, but that may not work, and the front end will show the local variable in red to give a warning. However, if I define a global variable to equal the local one, then I can use the global one inside Dynamic. Will this always work, or is it just a way to hide a problem that may occur? For example, this works:

Manipulate[
 Block[{data = RandomReal[{0, 1}, {2, 2}]}, dataG = data; 
  Dynamic@ArrayPlot[dataG^p]], {p, 0.1, 10}, 
 SynchronousUpdating -> False]

(In the present example, since the only effect on the plot of changing p is to change the color, one could also use ColorFunction.)

I stripped away many details from the application I have in mind. Rather than a simple data, I have a complicated calculation to do that depends on other control variables of the Manipulate. And that is the other reason for using Dynamic and why I want the local variable to be defined within Manipulate.

If this will not always work, is there a convenient way to introduce global variables so that they do not conflict with other global variables in the same session and without having to remember or check what has been used already?

One Answer

Two alternatives:

Using With (use multiple ones if necessary):

Manipulate[
 With[
  {data = RandomReal[{0, 1}, {4, 4}]},   
  Dynamic@ArrayPlot[data^p]],
 {p, 0.1, 10}, 
 SynchronousUpdating -> False]

Use a local variable with no control:

Manipulate[ 
 data = RandomReal[{0, 1}, {4, 4}]; 
 Dynamic@ArrayPlot[data^p],
 {p, 0.1, 10},
 {data, None}, 
 SynchronousUpdating -> False] 

One advantage of With is that it does not create a tracked symbol, which sometimes simplifies the Dynamic behavior of the Manipulate. Two disadvantages of With are that the variable is constant, and many nested With are inelegant.

Correct answer by Michael E2 on April 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP