MATLAB: How to continuously update data for two plots (plotted on the same axis using plot on)

animationaxeschildrendrawnowhold onloopobjectplotplot3springsubplotzdata

I have written a code to
  • Draw a spring
  • Draw a point on the spring
  • Animate the spring (up and down)
  • Animate the point to move along with the spring
Now, the animation works till the point where the spring alone has to move. If I try to plot the point, the animation stops and the spring and the point appear stationary.
I have plotted the spring and the point together on the same subplot (of an axes handle in a GUI). How can I update the Zdata of both the plots in a loop?
time = 0:pi/50:25*pi; % Time array
radius = 2; % Radius of the coil spring
height = 10; % Height of the coil spring
x = sin(time) * radius; % Compute x and y
y = cos(time) * radius;
z = height/(2*pi) * time; %Compute z which will be used later to animate
axis off
ha1 = subplot(1,2,1,handles.axes1);
set(ha1,'Position',[.016 .044 .142 .274]);
hold on
plot3(1.275, 1.545, 121.1, 'diamond',...
'MarkerFaceColor', [0.7 0.7 0.7]);
axis off ;
while 1
t=0; axis off;
for t= 0:1:1000
zaddf = sind(2.5*2*pi*t);
znewf = z + zaddf;
Zdataarray = {znewf , zaddf + 121.1} ;
hChildren1 = get(handles.axes1,'Children');
axis off
When I run this code, the ZDataarray variable (concept suggested by this answer) becomes a cell with two elements – one a [1 X 1251] array and the other a single numerical value. I am not able to set the ZData of both the plots in a loop.
When I try with this code,
the spring animation works perfectly on its own, without the point on it.
How can I update both plots simultaneously, in a loop?
Thanks in advance.

Best Answer

Can you not just keep hold of the output arguments of your two plot3 command so you have the handles to both the graphical objects then update both of them in individual instructions in your loop?
I've never tried updating two handles in one set instruction using a cell array so I'm not even sure what it does. I would just go for
hLine1 = plot3(x,y,z,...)
hLine2 = plot3(1.275, 1.545,...)
while 1
set( hLine1, 'ZData', zaddf + 121.1 );
set( hLine2, 'ZData', znewf );
as a setup, at least initially to see if it works. I wouldn't name my handles that, I'd name them something more meaningful, but I'm not sure precisely what each represents.
If you always keep the handles to the graphics objects you plot - i.e. the output of plot3 or plot or whatever plotting instruction you use then you have the handles of the objects you want to update and you can just update them directly. I very rarely need to resort to things like getting Children from axes or using findall to get hold of a graphics object because I just keep their handles when I plot them so I can access them directly. It doesn't matter then what setup of axes you have, whether they are subplots or whether the graphics are all on the same axes or different axes.