MATLAB For Dummies, 2nd Edition
Book image
Explore Book Buy On Amazon

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;
 pause(2);
 refreshdata;
end

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.

About This Article

This article is from the book:

About the book authors:

Jim Sizemore is professor of physics and engineering at Tyler Junior College. For over 25 years, Sizemore has worked in the semiconductor and software industries as a process engineer, device physicist, and software developer. John Paul Mueller has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: