oro777
oro777

Reputation: 1110

Axes and UserData in MATLAB

I would like to store some data in the axes handle in MATLAB. I am using the "UserData" property in order to do so. I have noticed that the "UserData" property been cleared by the plot command. Is this a normal behavior ? By plotting, I can understand that the XData and YData of the axis handle will update but why the UserData is cleared ?

Here you can find a sample code which shows my problem. I am using MATLAB 2014b.

figure
set(gca, 'UserData', 10)
disp(['UserData = ' num2str(get(gca, 'UserData'))]) % displays 10 in the command window
plot(1:10);
disp(['UserData = ' num2str(get(gca, 'UserData'))]) % displays no userdata, it is empty

Upvotes: 3

Views: 1347

Answers (1)

matlabgui
matlabgui

Reputation: 5672

@excasa comment is correct, some additional info for you.

The UserData is cleared because the default value for the NextPlot property is replace, I change this to add in all of my matlab as I mostly want to create multiple plots and then I use a cla on the axes when I want to clear it.

In your case what I would do is:

f = figure;
ax = axes ( 'parent', f, 'nextplot', 'add' );  % defining parent is good practice
plot ( ax, [1:10], 'ro' );
ax.UserData = 10;
plot ( ax, [1:10], 'k-' );

etc...

Note: Its good practice to define the axes as a variable and use that in all your commands rather than gca or gcf.

Upvotes: 4

Related Questions