How to Create Animation in MATLAB by Performing Data Updates - dummies

How to Create Animation in MATLAB by Performing Data Updates

By Jim Sizemore, John Paul Mueller

Directly changing a data source is one way to create animation in MATLAB. The technique involves creating a link between the plot data and the data source. You can create a local data source, such as a variable, to create the animation, but this technique is more likely used with external data sources.

YSource = [2, 0, 1, 4, 5, 2, 3];
Bar1 = bar(YSource);
set(Bar1, ‘YDataSource’, ‘YSource’);
set(gca, ‘YLim’, [0, 8]);
for i = 2:7
 YSource(3) = i;

The code begins with a simple bar chart. It then assigns the bar chart’s YDataSource to a variable, YSource. However, a change to YSource doesn’t automatically show up on the plot; you must also call refreshdata, as shown later in the code.

Adjusting the display of a plot is often necessary to accommodate the animation you provide. In this example, the plot would need to adjust for the higher data values added during the animation. The effect is disruptive because the viewer would focus on these adjustments. The call to change the YLim value eliminates this problem. Make certain that you check for adjustments of this sort in your own code.

The for loop modifies one of the values in YSource, waits for two seconds, and then calls refreshdata to make the change appear in the plot. What you see onscreen is an increase in one of the bars as the values change. The change simulates data changes that you might see in a real-world, real-time display.