How to | Evaluate Expressions inside Dynamic or Manipulate
Dynamic and Manipulate have holding attributes that are vital in making them work properly. However, those holding attributes can interfere with other structural operations you may want to perform. This "How to" covers some useful approaches for Dynamic, Manipulate, and other held constructs.
Please note that due to the nature of these examples, some of the outputs are not saved in the file. These examples will only make sense if you evaluate the inputs as you go along.
Start by creating a variable whose value is a list of numbers:
This next input creates a list of sliders such that the first slider dynamically changes the first value of the list of numbers, the second slider changes the second value, and so on:
You may want to create this list of sliders more easily, like with Table. The HoldFirst attribute of Dynamic can get in the way, preventing the values of the Table variable from filtering through into the expression. So the following naive attempt fails, and we literally see instead of , , and so on. Notice the syntax coloring of , warning you of this danger:
To overcome this, the scoping construct With can be used to immediately replace all instances of the local variable with its corresponding value:
Getting rid of the InputForm wrapper will give us the formatted sliders:
This same approach can be used in Manipulate, when building sets of controls. The following is a Manipulate whose first slider specifies how many other sliders are shown. The other sliders are wrapped in Panel for visual clarity. Note again the use of With in the Table that creates the sliders:
Here is a similar case, where the number of checkboxes associated with the data variable changes based on the values of other Manipulate controls:
Build a Manipulate with indexed controls:
You can also build a Manipulate with an arbitrary number of controls by building up the necessary structure of indexed controls directly. In this case, Block is used to prevent any global definitions of from interfering with these structural operations: