Mathematica教程

# Introduction to Manipulate

The single command Manipulate lets you create an astonishing range of interactive applications with just a few lines of input. Manipulate is designed to be used by anyone who is comfortable using basic commands such as Table and Plot: it does not require learning any complicated new concepts, nor any understanding of user interface programming ideas.
The output you get from evaluating a Manipulate command is an interactive object containing one or more controls (sliders, etc.) that you can use to vary the value of one or more parameters. The output is very much like a small applet or widget: it is not just a static result, it is a running program you can interact with.
This tutorial is designed for people who are familiar with the basics of using the Mathematica language, including how to use functions, the various kinds of brackets and braces, and how to make simple plots. Some of the examples will use more advanced functions, but it is not necessary to understand exactly how these work in order to get the point of the example.
Despite the length of this tutorial, it is only half the story. "Advanced Manipulate Functionality" provides further information about some of the more sophisticated features of this rich command.

## Manipulate Is as Easy as Table

At its most basic, the syntax of Manipulate is identical to that of the humble function Table. Consider this Table command, which produces a list of numbers from one to twenty.
Simply replace the word Table with the word Manipulate, and you get an interactive application that lets you explore values of n with a slider.
If you are reading this documentation inside Mathematica, you can click and drag the slider to see the displayed value change in real time (meaning that it changes while you are dragging the slider, not just when you release it). If you are reading a static form of the documentation, you will see the slider moved to an arbitrary position. (By default, it starts out on the left side, but in the following examples the slider has typically been moved away from its initial position.)
In both Table and Manipulate, the form {variable, min, max} is used to specify an "iterator", giving the name of the variable and the range over which to vary it.
Of course the whole point of Manipulate (and Table for that matter) is that you can put any expression you like in the first argument, not just a simple variable name. Moving the slider in this very simple output already starts to give an idea of the power of Manipulate.
Again, if you are reading this in a static form you will have to trust that the graph changes in real time when the slider is moved.
Note that the slider has an extra icon next to it which, when clicked, opens a small panel of additional controls. Here, the panel from the previous example is opened.
The panel allows you to see the numerical value of the variable, as well as set it in motion using the animation controls.
If you want to see the value of the variable without having to open the subpanel, you can add the option Appearance->"Labeled" to the variable specification. (Note the number displayed to the right of the plus sign, which is updated in real time as the slider is moved.)
This is also the first hint that Manipulate goes far beyond the relative simplicity of Table, both in its output and in the flexibility and range of what can be specified in the list of variables.
Just like Table, Manipulate allows you to give more than one variable range specification.
You can have as many variables as you like, including so many that a similar Table command would try to enumerate an unreasonably large number of entries.
You can open any or all of the subpanels to see numerical values, and you are free to animate many different variables at the same time if you like.
One way to think of Manipulate is as a way to interactively explore a large parameter space. You can move around that space at will, exploring interesting directions as they appear. As you will see in later sections, Manipulate has many features designed to make such exploration easier and more rewarding.

## Symbolic Output and Step Sizes

The previous examples are graphical, and indeed the most common application for Manipulate is producing interactive graphics. But Manipulate is capable of making any Mathematica function interactive, not just graphical ones.
Often the first issue in examples involving symbolic, rather than graphical, output is that you want to deal with integers, rather than continuously variable real numbers. In Table the default step size is 1, so you naturally get integers, while in Manipulate the default is to allow continuous variation (which you could think of as a step size of zero). Compare these two examples, and note that Manipulate allows values in between those returned by Table.
Functions involving algebraic manipulations, for example, often do nothing interesting when given noninteger parameter values. This Expand function never expands anything.
Fortunately it is trivial to add an explicit step size of 1 to the Manipulate command, yielding exactly the same set of possible values in Manipulate as is returned by Table.
With an explicit step size, the Expand example is much more interesting.
The fact that only one value is displayed at a time allows you to create examples that go far beyond what would be practical in a Table command. An important property of Manipulate output is that there is no fixed panel size or arbitrary limit as to how large the output panel can grow.
(In printed forms of this documentation, the slider is set fairly low to avoid wasting paper, but when moved all the way to the right, the output smoothly grows to cover many pages worth of vertical space.)
As with Table, if you use rational numbers for the minimum and step, you will get perfect rational numbers in the variable, not approximate real numbers. Here is an example that uses the formatting function Row to create a simple example of adding fractions.
You can even use end points and step sizes that are symbolic expressions rather than just plain numbers.

## Types of Controls

Manipulate supports a wide range of alternate ways of specifying variables, which generate different kinds of controls for those variables. This includes checkboxes, popup menus, and others in addition to sliders.
The principle is that for each variable, you ask for a particular set of possible values, and Manipulate automatically chooses an appropriate type of control to make those values conveniently available. For a typical numerical Table-like iterator, a slider is the most convenient interface.
You might, on the other hand, want to specify a discrete list of possible values (numeric or symbolic) rather than a range. This is done with an iterator of the form {variable, {val1, val2, ...}}.
(Note the extra level of list compared to the range specification.) If you ask for a small number of separate values, you will get a row of buttons.
If you ask for a larger number of discrete values, Manipulate will switch to using a popup menu.
If you use the specific values True and False, you will get a checkbox.
These choices are of course somewhat arbitrary, but they are designed to be convenient, and you can always override the automatic choice of control type using a ControlType option inserted into the variable specification. (The full list of possible control types is given in the documentation for Manipulate.)
For example, you can ask for a row of buttons even if the automatic behavior would have chosen a popup menu, using the option .
Sliders can be used to scan through discrete symbolic values, not just through numerical ranges (and this allows you to animate through them as well). The option asks for the default control used by Manipulate, which is a slider plus an optional control panel with numerical value and animation controls (see the previous example). asks for a plain slider.
It is even possible to use two different controls to adjust the value of the same variable. Here both a popup menu and a slider are connected to the value of the filling variable. If the slider is used to select a value that does not appear in the popup menu, the popup will appear blank, but remains functional. When a value is chosen from the popup menu, the slider is moved to the corresponding position. Both controls can thus be used interchangeably to adjust the same value, and each one follows along when the other is being used.
This is not an exhaustive list of the possible control types in Manipulate. See the Manipulate documentation for a more detailed listing. One of the most important control types, Locator, which allows you to place control points inside graphical output in a Manipulate, is discussed in "Locator"; Slider2D is discussed in the "2D Sliders" section.

## Initial Values and Labels

Here is a fun example for making Lissajous figures.
Unfortunately you see nothing at first: until you move the a1 and a2 (amplitude) variables away from their initial values of zero, there is nothing to see. It would be convenient to set their initial value to something other than the default left-most value. This is done by using a variable specification of the form {{var, init}, min, max}.
Here is the same example with both amplitudes set to 1 initially, and the default frequency values set to give a pleasing initial figure.
It is fun to watch how one shape turns into another, and in this connection it is good to know about an unusual feature of sliders in Mathematica. If you hold down the Option key (Macintosh) or Alt key (Windows), the action of the slider will be slowed down by a factor of 20 relative to the movements of the mouse. In other words, when you drag the mouse left and right, the thumb will move only 1/20th as much as it normally would. If you move outside the area of the slider, the value will start moving slowly in that direction as long as the mouse remains clicked.
By holding down the Shift or Ctrl keys, or both, in addition to the Option/Alt key, you can slow the movement down by additional factors of 20 (one for each additional modifier key). With all three held down, it is possible to move the thumb by less that one part per million of its full range, which can be helpful in examples like this where beautiful patterns are hidden in very small ranges of parameter space.
(The option PerformanceGoal->"Quality" is used in this example to ensure that ParametricPlot draws smooth curves even when a slider is being moved: the need for this option is explained in more detail in "Advanced Manipulate Functionality".)
By default Manipulate uses the names of the variables to label each control. But you may want to provide longer, more descriptive labels, which can be done by using variable specifications of the form {{var, init, label}, min, max}.
Here is the same example with labels.

## Beautifying the Control Area

Manipulate supports a number of features that allow you to rearrange, annotate, and generally pretty up the control area, to make it suit the needs of a particular example. (Advanced users should remember, however, that Manipulate is by no means the only way to create interactive interfaces in Mathematica, and if you cannot do what you want using Manipulate, you can easily start using functions such as Dynamic and DynamicModule directly to create free-form, open-ended user interfaces not tied to the particular conventions of Manipulate. These features are explained in detail in "Introduction to Dynamic" and "Advanced Dynamic Functionality".)
When you have a small number of controls, it is usually most convenient to have them above the content area of the Manipulate panel. But because screens are typically wider than they are tall, if you have a large number of controls, you may find it better to put them on the left side, using the ControlPlacement option.
When ControlPlacement is used at the level of the Manipulate as a whole, it sets the default position of all the controls. But the option can also be used inside individual variable specifications, allowing you to distribute controls to multiple sides of the output field.
In the following example the controls naturally fall into two groups of three, or three groups of two. You can use the keyword Delimiter inserted in the sequence of variable specifications to indicate where you would like dividing lines put. Here two unlabeled delimiters break the controls up into three groups.
Alternately strings, or delimiters and strings, can be used to label the groups of controls.
Quite a variety of things can be interspersed with the controls, including styled text, arbitrary expressions, and even dynamic objects that update independently of the main output window. Here is a simple example of using Style to make the group headings more prominent.
Examples of more complex arrangements and dynamic labels are shown in "Advanced Manipulate Functionality".

## 2D Sliders

A clever feature of Mathematica is support for two-dimensional sliders, which allow you to use both directions of mouse movement to control two values simultaneously. (Ordinary one-dimensional sliders in a sense waste one of the two degrees of freedom a mouse is capable of.)
To get a 2D slider, use pairs of numbers for both the min and max, as in {var, {xmin, ymin}, {xmax, ymax}}
The value of the variable will also be an {x, y} pair. In this trivial example, just look at the value of the variable to get a feel for how the control works.
The following example shows more graphically how the value of a 2D slider corresponds to a coordinate point.
To do something more interesting, you can recast the Lissajous figure from the previous section with three 2D sliders instead of six 1D sliders. You are controlling the same six parameters, but now you can do it two at a time.
This creates an example that is compact and fun. Note that fine control using the Option, Shift, and Ctrl keys to slow down the motion of sliders (as explained in "Initial Values and Labels") works for 2D sliders as well as 1D sliders.

## Graphics beyond Plotting

So far high-level plotting functions have mostly been used, but it is equally interesting to use Mathematica's low-level graphics language inside Manipulate. The following example, repeated from the previous section, is a trivial example of using the low-level graphics language.
This example also makes the important point that anytime you use Graphics inside Manipulate, you probably want to set an explicit PlotRange option. (PlotRange->1 means 1 in all directions from the origin, and is equivalent to PlotRange->{{-1, 1}, {-1, 1}}.) If you omit the PlotRange option Mathematica's automatic plot range determination will cause the dot to appear not to move at all, because the plot range is always exactly centered around it.
Simple (or complicated) Mathematica programming can add arbitrary graphical elements to the output. For example, here we have lines to the center point instead of a dot, with a second linear slider determining the number of lines.
Here is a fun little string-figure example also based on creating a table of lines.
Because Mathematica is a sophisticated programming language, it is possible to use Manipulate to explore parameterized programs or algorithms interactively. The Mathematica graphics language is explained in "The Structure of Graphics", and many more examples like this can be found in The Wolfram Demonstrations Project.

## Locator

For creating interactive graphics examples, one of the most important features of Manipulate is the ability to place a control point, called a Locator, inside graphics that appear in the output area.
Consider the previous example with lines going to a center point. While using a 2D slider is a fine way to control the center point, you might prefer to be able to simply click and drag the center point itself. This can be done by adding Locator to the control specification for the pt variable. In this case it is not necessary to specify a min and max range, because it can be taken automatically from the graphic. (It is, however, necessary to specify an initial value.)
Now you can click anywhere in the graphic and the center point of the lines will follow the mouse as long as you keep the mouse button down. (It is not necessary to click exactly on the center; it will jump to wherever you click, anywhere in the graphic.)
You can have multiple Locator controls by listing them individually, and it is perfectly fine to have a Manipulate with no controls outside the content area, so you can create purely graphical examples.
When there are multiple locators, you can still click anywhere in the graphic, and the nearest Locator will jump to where you click and start tracking the mouse.
Instead of using multiple separate variables, each of which corresponds to a single {x, y} point, you can use a single variable whose value is a list of points.
Again, if you click anywhere in the graphic, not on a particular Locator, the nearest one will jump to the mouse and start tracking it.
Due to internal limitations, it is not possible to combine individual Locator variables with a variable that is a list of multiple Locator variables: you can have only one multipoint Locator variable in a Manipulate. However, in exchange, it is possible to add the option to that one Locator multivariable specification, and thereby allow you to create and destroy Locator points interactively (changing the length of the list of points stored in the variable).
In the following example, hold down the Cmd key (Macintosh) or Alt key (Windows) and click anywhere that is not an existing Locator to create a new one at that location. Cmd/Alt click an existing Locator to destroy it. When you add or remove a Locator, you are changing the length of the list of points stored in the pts variable, thus changing the number of vertices in the displayed polygon.
You can of course combine Locator controls with normal Manipulate variables. For example, you can use some sliders and color choosers to control the appearance of the polygon.
While a case can be made that the previous examples are frivolous, they are meant to demonstrate the generality of the system: it provides a framework inside of which anything is possible. And the following example shows that even just a couple of lines of code can do something quite remarkable: create an interactive polynomial curve-fitting environment.
The locator thumbs represent data points that are being fit by least squares with a polynomial whose order is determined by the "order" slider. Five points are provided initially, but you can add new ones by Cmd/Alt clicking any blank area of the graphic, or remove one by Cmd/Alt clicking it.
The fact that an example of this sophistication can be constructed using such a small volume of code is really quite remarkable. And if you want to really impress someone with the compactness of Mathematica code, the following example shows how to do it using only two lines, with some loss of generality. Practice a bit and you can type this from scratch in 30 seconds or less.

## 3D Graphics

Manipulate can be used to explore 3D graphics just as easily as 2D, though performance issues become more of a concern. Consider this simple example.
For large values of n the function oscillates rapidly, and in order to produce a smooth picture, the default adaptive sampling algorithm in Plot3D produces a fairly large number of polygons, with correspondingly long computation and rendering times.
Fortunately, Plot3D and other built-in plotting functions automatically adjust their internal algorithms and settings when used inside Manipulate in order to deliver increased speed while a control is being dragged, sometimes at the expense of rendering quality. As soon as the mouse button is released, a high-quality version of the plot is generated asynchronously (meaning other operations in the front end can continue while the plot is being generated). Asynchronous evaluations are discussed in further detail in "Synchronous Versus Asynchronous Dynamic Evaluations" in "Advanced Dynamic Functionality".
The net result is that while you drag the slider, a fast, but somewhat crude, rendering of the plot is created in real time, and when you release the control, a smooth rendering shows up a moment later. (This happens because Plot3D, and most other plotting functions, refer to the function ControlActive in the default settings of the various options that control rendering quality and speed. See "Dealing with Slow Evaluations" in "Advanced Manipulate Functionality" for more about using ControlActive within Manipulate.)
As in 2D, you can use the low-level graphics language just as easily as higher-level plotting commands. In this example you can see how Mathematica handles spheres that intersect with each other and with the bounding box.
This example shows how opacity (which is to say, transparency) can be used to see inside nested 3D structures.
(Note that adding transparency to a 3D graphic can slow down rendering significantly.)
You can rotate a 3D graphic inside a Manipulate output by clicking and dragging it in the ordinary way. In most cases if you subsequently move one of the Manipulate controls, the graphic will stay rotated to the position you moved it to manually, unless the graphics expression in the Manipulate contains an explicit ViewPoint option, or wraps the graphical output in additional formatting constructs.

## All Types of Output Are Supported

Manipulate is designed to work with the full range of possible types of output you can get with Mathematica, and it does not stop with graphical and algebraic output. Any kind of output supported by Mathematica can be used inside Manipulate. Here are some examples which may be less than obvious.
Formatting constructs such as Grid, Column, Panel, etc. can be used to produce nicely formatted outputs. (See "Grids, Rows, and Columns" for more information about formatting constructs.)
You can even wrap Manipulate around functions that generate user interface elements like sliders and tab views. (See "Control Objects" and "Viewers and Annotation" for more information about user interface elements.) In this example we use two sliders to control the appearance of a third slider.
In this more complicated example the structure of a TabView is controlled by a Manipulate. Dynamic[pane] allows the current pane of the TabView to be selected either by using the slider created by Manipulate, or by clicking the TabView in the output area. The output is fully active.
This example may be somewhat alarming, but is meant only to illustrate that Manipulate is a fully general function, not limited to exploring any fixed domain of graphical or algebraic examples. There is literally nothing you can see in a cell in a Mathematica notebook that you cannot interactively explore using Manipulate (subject only, of course, to the speed of your computer).

## Saving Definitions of Functions Used inside Manipulate

Suppose you define a function, then use it in the first argument of a Manipulate.
This example will work well, until you try saving it in a file and then reopening it in a fresh session of Mathematica. Then the function f will not be defined until you manually evaluate the cell containing its definition. (In fact, if you are reading this documentation inside Mathematica you will see f appearing in the output area of the Manipulate at first, for exactly this reason.)
Manipulate supports the option , which causes it to automatically build into the Manipulate output a copy of all the definitions of functions referred to in the Manipulate input (and recursively any functions they refer to). These definitions are then reestablished in any new Mathematica sessions the Manipulate output is opened in, before contents of the Manipulate are evaluated for the first time.
Thus if you are reading this inside Mathematica, the second example should correctly display a number even when first opened.
You can use SaveDefinitions to store function definitions or datasets, but be warned that if you refer to a large volume of data, it will of course be present in the file containing the saved Manipulate output, potentially creating a very large file.
An alternative in such a case is to use the Initialization option to load a package of data from a file or other source, rather than building it into the Manipulate output. The Initialization option can be given any arbitrary block of Mathematica code to be evaluated before the contents of the Manipulate are first evaluated in any fresh session of Mathematica. The right-hand side of the Initialization option will be evaluated only once per session.
For example, you can achieve the same result as earlier using the Initialization option instead of SaveDefinitions.
You can think of SaveDefinitions as a convenient automatic way of setting an Initialization option with all the definitions you need to run the example. (SaveDefinitions does not actually interfere with the use of the Initialization option: you can use both if you like.)

When interacting with a Manipulate output using a mouse, you are limited to moving only one control at a time. However, there are many USB controller devices available which overcome this limitation by placing a button or joystick under each finger, thus greatly increasing the number of controls you can move simultaneously.
In order to take advantage of a USB controller in Manipulate, all you have to do is plug it in, and use the mouse to select (highlight) the cell bracket containing the Manipulate output you want to control. Mathematica automatically detects the controller, and Manipulate automatically links as many parameters as possible with the available joysticks and buttons.
While Mathematica will work, or attempt to work, with any USB controller device (gamepad, joystick, simulated airplane throttle control—even data acquisition devices that use the USB controller interface standard), some definitely work better than others for controlling Manipulate outputs. Generally speaking, dual-joystick gamepads, such as commonly used with video games, provide a good set of controls, typically four analog axes and a large number of buttons.
For the remainder of this section we will assume you are using a Logitech Dual Action gamepad. (This inexpensive controller is widely available and has better mechanical and electrical performance than many other units, even significantly more expensive ones.) If you are using a single joystick or another brand of gamepad there may be some differences in which controller parts map to which Manipulate parameters.
With a gamepad plugged in, select the cell bracket of the cell containing the following output. Initially nothing will happen, because the gamepad's joysticks are in their neutral, undeflected position. But if you move them, you will see one or more of the parameters start to change. The rate at which the parameter changes is proportional to the degree of deflection of the joystick.
By default, Manipulate connects the x axis of the left gamepad to the first parameter, the y axis of the left joystick to the second parameter, the x axis of the right joystick to the third parameter, and the y axis of the right gamepad to the fourth parameter. You can verify this by moving each joystick in a given direction and watching which parameter changes. (If you are using something other than a Logitech Dual Action gamepad you may see a different mapping: each manufacturer does things a bit differently, and while Mathematica has tables that attempt to normalize many commonly available controllers, new ones are always being introduced.)
By default, the mapping is "velocity-based", which is to say that the rate at which the parameter changes is controlled by the position of the joystick. The joystick position is thus not directly connected to the value of the variable.
You might instead want the value of the variable to be determined by the absolute position of the joystick, and there are two ways to achieve this. On many gamepads, including the recommended Logitech model, the joysticks are also buttons: if you press down on a joystick it clicks like a button, and when the joystick is controlling a Manipulate, this causes the corresponding parameter(s) to become directly linked to the position of the joystick. You can use this direct mode to rapidly jump to any position, then release the joystick to stop the parameter value there.
If your gamepad does not have buttons in the joysticks, or you just want the linkage to always be direct, you can use the option ControllerMethod->"Absolute".
Note that there are disadvantages to direct linkage, most notably that as soon as you highlight the cell bracket (with a gamepad connected), all of the parameter values immediately jump to their middle positions, which is of course what they must do if the joysticks are in their neutral positions. While you can still use the mouse to set values, they will be overridden by the gamepad as soon as it is touched.
A small variation on velocity control can be had with the option ControllerMethod->"Cyclic". With this setting the linkage is velocity-based, but when you reach one end of the parameter's range of values, instead of stopping it cycles around to the opposite end.
Whether direct or velocity-based linking is best depends on the example. The previous example is generally more satisfactory with velocity linking, while the following example is definitely better with direct linking.
If any of these examples seem not to be working, chances are it is because you have forgotten to highlight the cell bracket containing them. This is a common mistake. As a convenience, and to avoid the need to select each output as soon as it is generated, if you wiggle any gamepad controller immediately after generating an output that references controllers, Mathematica will automatically select the output cell for you. But this only happens immediately after the output is generated, after that it is up to you to choose, by selecting it, which Manipulate output you want the controller connected to.
If you want a given Manipulate to always respond to the controller whether it is selected or not, you can add the option , but this feature should be used with caution. If you have multiple such outputs on screen, they will all attempt to move simultaneously, which is rarely helpful. The option is best used in situations where you are creating a fixed-format output window, rather than when creating examples meant to be used in a scrolling document such as this one.
In examples like the previous one, which do not make much sense unless you have a gamepad available, it is often pointless to display the sliders associated with the parameters, or the rest of the framework of Manipulate. The function ControllerManipulate is basically identical to Manipulate in all its features and syntax, except that it does not display any frame or sliders.
Manipulate will continue to be used in subsequent examples because it is helpful to be able to see the controls to understand how they are being affected by the gamepad, but many of these examples would look and work just as well with ControllerManipulate.
If the Manipulate contains Slider2D variables, whose values are {x, y} pairs of numbers, they will automatically be linked to both directions of available joysticks. This example responds in both directions to the left-hand joystick on a gamepad.
Push buttons on the controller are by default linked up to any Boolean (True/False) parameters specified in the Manipulate. Which button is which can be a bit hard to guess on a given controller (a concept which is explained elsewhere), but on the Logitech model the group of four buttons on the right side are labeled 1 through 4, and are used by Manipulate in that order. In this example clicking the "1" button toggles the setting of b1, changing the color of the point.
This toggling behavior (flipping the value of the parameter once each time the button is pressed) is the equivalent of velocity-based linking. If you use the ControllerMethod->"Absolute" option (see previous examples) the parameter will be linked directly, which is to say its value will be False all the time except while the button is actually being held down.
The exact rules by which Manipulate connects controller axes to parameters are somewhat complex, but basically they try to allocate the available analog and Boolean controls to the parameters in the Manipulate so as to make maximum use of the available joysticks, buttons, knobs, and other widgets on the controller. (Often the quickest and easiest way to figure out what has been linked to what is simply to wiggle the various knobs and see what happens.)
If you find that the default linking is not to your liking, it can be overridden by explicitly stating which controller axis should be connected to which parameter. The controller axes are named according to a logical system, but for most purposes it is enough to remember a few basic names: "X", "Y", "XY", "X1", "X2", "B1", "B2", etc.
"X", or its synonym "X1", refers to the x axis of the primary, or the left-hand joystick on the gamepad. To specify that a parameter should be linked to this axis, use the following form.
"X2" similarly refers to the x axis of the secondary, or right-hand joystick.
Axes can be combined into multidimensional parameters. For example, "XY" refers to both directions of the left or primary joystick, combined into a single {x, y} value. Such a combined axis must be connected to a Slider2D style of parameter, as in this example.
Three-axis variables are also supported as "XYZ". When using a three-axis joystick controller, the axes will correspond to the three degrees of freedom of the joystick. When using a dual-joystick gamepad, each joystick only has two degrees of freedom. In this case the "XYZ" axis is linked to the x and y directions of the left joystick plus the x direction of the right joystick. Whether this makes sense depends on the example: examples written specifically to take advantage of a three-degrees-of-freedom joystick may not work well with any other kind of controller.
Some controllers actually provide 6 analog degrees of freedom, which can be referred to as "XYZ" and "XYZ2". For example, if you have a 3Dconnexion SpaceNavigator control, the following example will let you explore its three spatial and three angular degrees of freedom. If you do not have one, the example will be unsatisfactory.
(Note that 3D variables in Manipulate are available whether you are using a controller or not, but are not generally useful other than in connection with a joystick or gamepad.)
A typical gamepad has two x-y controllers, named "XY" and "XY2". But what is less obvious is that there are also several more pseudo-analog axes available, generated by considering groups of four buttons as four directions: up, down, left, and right. For example, the "hat", a directional pad on the left side of a Logitech Dual Action gamepad, can be referenced as "XY3".
Two additional axes ("XY4") are defined by the four buttons on the right side of the gamepad, and the four buttons on the front face ("XY5"). Needless to say this is highly specific to the Logitech brand of controller, but others typically have similar groups of buttons.
These pseudo-analog axes act just like real analog ones, except that in velocity-linked mode they always progress at the same speed, and in absolute mode they are always pegged at the full-left, center, or full-right positions.
When attempting to hook up specific axes it is often confusing trying to figure out which one is which on a given controller. The function can be used to figure this out interactively. With your gamepad or joystick plugged in, evaluate this input (you have to evaluate it in your session of Mathematica with your controller plugged in to get current information).
Depending on what type of computer you are using you may get several built-in controls. For example, Macintosh laptops typically contain a position sensor that reads out the orientation of the computer at all times. This information is available and can be used with Manipulate, but is not used by default (otherwise all Manipulate functions that run on such laptops would constantly move around as you tilted the computer, which some might consider a nuisance).
Locate the controller you want to examine and click the disclosure triangle next to its name to open a panel of information, then open the Mathematica Controls subsection to see a list of all the available axis names.
If Show Dynamic Values is checked, the values displayed in the panel will update in real time as you wiggle the controller or push its buttons, allowing you to easily determine which button corresponds to which named axis. (Do not forget the quotes around the axis names when using them in Manipulate.)
The option ControllerMethod can only be used at the level of the whole Manipulate to change the linking from velocity-based to absolute. If you want to make some axes absolute and some velocity-based, add "Absolute" to the name of any axes you want to have linked absolutely, as in this example, which has a velocity-based x direction and an absolute y direction.
The opposite of "Absolute" in this notation is "Relative", as in "XRelative", etc.

## Autorun

In many ways Manipulate is a big improvement over simple linear animations. Rather than running through a fixed sequence, Manipulate lets you move back and forth at will. But what if you do not want to have to move a slider by hand? One option is to use the icon next to each slider to open a panel with animation controls. A Manipulate with one variable being animated is virtually equivalent to Animate.
But if you have multiple variables and want to see the effect of changing all of them, it is inconvenient to use the individual animation controls. The Autorun feature of Manipulate solves this problem by providing a single animation control that runs all the variables through their ranges of values.
Click the menu in the top right corner of a Manipulate output and select Autorun from the bottom of the menu. You will see an Autorun panel appear at the top of the Manipulate, containing animation controls and a button. By default the animation runs each individual variable through its range of values, leaving the others at their default values. As with any animation control, you can change the speed and direction, or click the slider to move through the animation manually. The Autorun animation slider acts as a sort of master control driving all the other controls in a defined order.
The default behavior of Autorun simulates something you could do yourself with the mouse, moving one control at a time. If you add the option to the Manipulate input, the Autorun command in the resulting output will instead move all the controls simultaneously, as you can see in this example. This feature works better for some examples than for others.
You can also use AutorunSequencing to exclude certain controls from the Autorun animation, or change the order in which the controls are animated. In the following example, the third control is animated first, then the first control, then the fourth, and the second control is left at its default value.
AutorunSequencing allows you to specify the duration reserved for the animation of a particular control. This setting reserves two seconds for the first control, two seconds for the third control, and ten seconds for the fourth control. The second control is skipped as before.
One reason to care about the details of AutorunSequencing is that it is possible to use the Export command to automatically generate an animation video (in, for example, QuickTime or Flash format). By default Export will generate an animation by running the Manipulate through one Autorun cycle.
If AutorunSequencing does not give you enough control over the animation sequence, you can use the Bookmarks feature described in the next section to define a list of "way points"—combinations of parameter values—and then create an animation that smoothly interpolates through those defined points. This allows complete control over the exact path of the animation.

## Bookmarking Combinations of Parameter Values

Manipulate functions, particularly when they have many controls, can be used to find a needle in a haystack: a particular combination of multiple parameter values that yields a particularly interesting result. When you have found a set of values like that, you might want to save it for future reference. Manipulate provides several features for doing this through the menu in the top-right corner of the Manipulate output.
To get a single value out into a form you can use as a static input, use the Paste Snapshot command from the menu. The result will be inserted as a new cell below the Manipulate output.
Here is the result of using Paste Snapshot with this example.
The three current values have been copied into the variable definition block of a DynamicModule, and the first argument has been copied into the body. (DynamicModule is used because in cases where the body contains explicit uses of Dynamic this will result in more correct functioning. Depending on what you want to do with the result, you are of course free to replace DynamicModule with Module, With, or Block without needing to make any other changes to the expression. Or you can copy/paste the block of assignments into other code you are building, etc. The differences between Module and DynamicModule are discussed in further detail in "Advanced Dynamic Functionality".)
If, instead of immediately extracting that location, you just want to remember it so that it is easy to visit in the future, select Add To Bookmarks from the menu. That will bring up a panel that will let you name the bookmark and add it to list of bookmarks which are known to this Manipulate by clicking the button, or cancel the addition by clicking the button.
After adding a bookmark, the name you have specified for it will appear in the menu. Selecting its name from that menu will cause all the parameters to snap back to the values they had when that bookmark was added. Also note that every Manipulate remembers the initial settings of all its controls, and you can snap back to those values by choosing Initial Settings in this menu.
Once you start placing bookmarks, there are two other items in the menu which become relevant: Paste Bookmarks and Animate Bookmarks.
Bookmarks are lists of locations in a given parameter space, and you can extract the raw data in that list by choosing the Paste Bookmarks item. Every element of the resulting list is of the form bookmarkName:>parameterValues. This list is syntactically appropriate for reinserting into Manipulate input as the setting for the Bookmarks option. (This allows you to, for example, modify the bookmarks by manual editing, or run a program on them, before restoring them as active bookmarks in a new Manipulate output.)
The Animate Bookmarks menu command works much like the Autorun command described in the previous section, except that instead of animating each parameter through its range of values, it creates an animation that interpolates through the points specified by the bookmarks.
The interpolation which occurs when animating bookmarks is done internally via the Interpolation command. Manipulate even accepts the InterpolationOrder option to adjust how the animation proceeds from one point to the next. The default value of Automatic performs quadratic interpolation if there are enough bookmarks, and linear interpolation otherwise.
When a Manipulate output containing explicit bookmarks is exported to a video animation format using Export, the resulting video will be one cycle through the sequence generated by Animate Bookmarks. (If no bookmarks are present, the result is one cycle of Autorun.)