MATLAB: Error: invalid or deleted object when using scatter in axes in GUI

guihandlesplotscatter

Hello,
The following is a snippet of code from a function I am writing to create a GUI for visualizing data.
% Create axes for the scatterplot
theaxes2 = axes('Parent',thefigure, ...
'Units','Normalized', ...
'Position',[0.55 0.125 0.4 0.7]);
xlabel('PC 2');
ylabel('PC 3');
title('Principal Component Scatterplot');
% test that I can plot data on the theaxes2
scatter_handle = scatter(theaxes2, rand(10,1), rand(10,1));
Where I am using scatter just to test that I can throw data onto to the axes I just created. (This after it failing when I tried to plot real data further down the line)
That last line returns the error:
Error using handle.handle/set Invalid or deleted object.
This error occurs even if I replace theaxes2 with gca.
The error does NOT occur if I use line instead of scatter. (e.g. handle = line('parent', MYINFO.fileinfo{nfile}.theaxes2, 'xdata', 1:30, 'ydata', 1:30);)
But it does fail if I use "plot".
Here's the really weird thing. After the function has thrown the error and returned without completing the GUI, and I have the half-built GUI, if I paste that last line (using gca instead of the variable theaxes2) into the command line, it works fine.
I am tearing my hair out here. I have no idea why this won't work inside my function but will work if I create a figure from the command line and use the same function. How has the handle become invalid?
Thanks so much for your help.

Best Answer

An axes() call with properties does not make the new axes the current axes.
Try using
xlabel(theaxes2, 'PC 2');
ylabel(theaxes2, 'PC 3');
title(theaxes2, 'Principal Component Scatterplot');
scatter_handle = scatter(theaxes2, rand(10,1), rand(10,1));
However, it would be safer to do the scatter() first and then label and title.