Question

I need to create a movie. Suppose, I create an axis and plot on it something very customized:

figure;
ax = plot(x, y, 'linewidth', 3, 'prop1', value1, 'prop2', value2, ...);
grid minor;
axis(ax, [xmin xmax ymin ymax]);
legend(ax, ...);
xlabel(ax, ...);
ylabel(ax, ...);
title(ax, ...);

Now I run a loop, where only the values of y are being updated.

for k = 1 : N
% y changes, update the axis
end

What is the fastest and easiest way to update the axis with new y (or x and y), keeping all the axis properties?

Was it helpful?

Solution

A fast way is to simply update the y-values of the data you've plotted:

%# note: plot returns the handle to the line, not the axes
%# ax = gca returns the handle to the axes
lineHandle = plot(x, y, 'linewidth', 3, 'prop1', value1, 'prop2', value2, ...);

%# in the loop
set(lineHandle,'ydata',newYdata)

EDIT What if there are multiple lines, i.e. lineHandle is a vector? You can still update in one step; you need to convert the data to a cell array, though.

%# make a plot with random data
lineHandle = plot(rand(12));

%# create new data
newYdata = randn(12);
newYcell = mat2cell(newYdata,12,ones(1,12));

%# set new y-data. Make sure that there is a row in 
%# newYcell for each element in lineH (i.e. that it is a n-by-1 vector
set(lineHandle,{'ydata'},newYcell(:) );

OTHER TIPS

Just pass the axis handle back to subsequent plot commands

i.e.

plot(ax, ...)

rather than

ax = plot(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top