1
votes

I want to plot data, which is stored in an array. A contains three columns, each column represents a different data set. The following code works fine:

A = [0 0 0;
    0 1 0];
h = plot(A)

However, a new line is appended to A and the plot shall be updated. I read that you can update plots with set and 'XData':

A = [0 0 0;
    0 1 0;
    1 2 0];
set(h,'XData',A)

This throws me an error: Error using set. Value must be a column or row vector. Is there any way to refresh the data instead of a new plot? The following works just fine?

A = [0 0 0;
    0 1 0;
    1 2 0];
h = plot(A)
2

2 Answers

4
votes

The initial code

A = [0 0 0;
    0 1 0];
h = plot(A)

generates three line objects, one for each column of A (check that h has size 3×1). So you need to update each of those lines in a loop. Also, you need to update both the 'XData' and 'YData' properties:

for k = 1:numel(h)
    set(h(k), 'XData', 1:size(A,1), 'YData', A(:,k))
end
2
votes

You could use linkdata (https://mathworks.com/help/matlab/ref/linkdata.html):

A = [
  0 0 0;
  0 1 0
];

plot(A);
linkdata on;

A = [
  0 0 0;
  0 1 0;
  1 2 0
];

Another approach deleting the plot and redrawing it immediately after:

h = plot(x,y);

% modify data...

delete(h);
h = plot(x,y);