MATLAB: How to update YData of multiple subplots

handlesMATLABsubplot

In my script I create a few plots in the init code and then I want to update the plot content in my main code. To improve performance I want to avoid plotting again and again, because this gets quite slow for bigger data sets. That's why I try to set the YData of the plots, but I get the error "Invalid or deleted object" at the code line, where I set the Ydata.
This is the init code:
% Create plots
% Channel 1
subplot(3,1,1);
h1 = plot(t, RecBuf(:,1));
ylim([0 1]);
xlabel('t /s');
ylabel('Ouput (norm. to 1)');
hold on;
% Channel 2 to 8
subplot(3,1,2);
h2 = plot(t, RecBuf(:,2:8));
xlabel('t /s');
ylabel('Ouput (norm. to 1)');
hold on;
And this is the code where I try to update the data. set(h1,…) throws the error.
% Plot Ch 1
subplot(3,1,1);
cla;
%plot(t, RecBuf(:,1));
set(h1, 'YData', RecBuf(:,1));
% Plot Ch 2 to 8
subplot(3,1,2);
cla;
plot(t, RecBuf(:,2:8));
Why would the handle to the plot be invalid?

Best Answer

h1 is an object on subplot(3,1,1).
subplot(3,1,1);
h1 = plot(t, RecBuf(:,1));
Then you clear everything from that subplot using cla()
subplot(3,1,1);
cla;
So when you update the YData property, the object has already been deleted.
set(h1, 'YData', RecBuf(:,1)); % ERRROR
Why are you clearing the axes (cla) ?