MATLAB For Dummies
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:

John Paul Mueller is an author and technical editor with experience in application development, database management, machine learning, and deep learning. He has written hundreds of books and articles helping everyday people learn everything from networking to database management.

John Mueller has produced 114 books and more than 600 articles on topics ranging from functional programming techniques to working with Amazon Web Services (AWS). Luca Massaron, a Google Developer Expert (GDE),??interprets big data and transforms it into smart data through simple and effective data mining and machine learning techniques.

This article can be found in the category: