Graphics objects are complex structures that store information (data and object characteristics), listen for certain events to occur (callback properties), and can cause changes to other objects to accommodate their existence (update to axes limits, and so on). Therefore, creating an object consumes resources.
When performance becomes an important consideration, try to realize your objectives in a way that consumes a minimum amount of resources.
You can often improve performance by following these guidelines:
Do not create unnecessary objects
Avoid searching the object hierarchy
Look for cases where you can create fewer objects and achieve the same results. For example, suppose you want to plot a 10-by-1000 array of points showing only markers.
This code creates 1000 line objects:
x = rand(10,1000); y = rand(10,1000); plot(x,y,'LineStyle','none','Marker','.','Color','b');
Convert the data from 10-by-1000 to 10000-by-1. This code creates a graph that looks the same, but creates only one object:
If coordinate data contains NaNs, MATLAB® does not render those points. You can add NaNs to vertex data to create line segments that look like separate lines. Place the NaNs at the same element locations in each vector of data. For example, this code appears to create three separate lines:
x = [0:10,NaN,20:30,NaN,40:50]; y = [0:10,NaN,0:10,NaN,0:10]; line(x,y)
To view different data on what is basically the same graph, it is more efficient to update the data of the existing objects (lines, text, etc.) rather than recreating the entire graph.
For example, suppose you want to visualize the effect on your data of varying certain parameters.
Set the limits of any axis that can be
determined in advance, or set the axis limits modes to
Recalculate the data using the new parameters.
Use the new data to update the data properties of the lines, text, etc. objects used in the graph.
drawnow to update
the figure (and all child objects in the figure).
For example, suppose you want to update a graph as data changes:
figure z = peaks; h = surf(z); drawnow zlim([min(z(:)), max(z(:))]); for k = 1:50 h.ZData = (0.01+sin(2*pi*k/20)*z); drawnow end