Main Content

Copy Objects

Copying Objects with copyobj

Copy objects from one parent to another using the copyobj function. The copy differs from the original:

  • The Parent property is now the new parent.

  • The copied object’s handle is different from the original.

  • copyobj does not copy the original object’s callback properties

  • copyobj does not copy any application data associated with the original object.

Therefore, == and isequal return false when comparing original and new handles.

You can copy various objects to a new parent, or one object to several new parents, as long as the result maintains the correct parent/child relationship. When you copy an object having child objects, MATLAB® copies all children too.

Note

You cannot copy the same object more than once to the same parent in a single call to copyobj.

Copy Single Object to Multiple Destinations.

When copying a single object to multiple destinations, the new handles returned by copyobj are in the same order as the parent handles.

h = copyobj(cobj,[newParent1,newParent2,newParent3])

The returned array h contains the new object handles in the order shown:

   h(1) -> newParent1
   h(2) -> newParent2
   h(3) -> newParent3

Copying Multiple Objects

This example shows how to copy multiple objects to a single parent.

Suppose that you create a set of similar graphs and want to label the same data point on each graph. You can copy the text and marker objects used to label the point in the first graph to each subsequent graph.

Create and label the first graph:

x = 0:.1:2*pi;
plot(x,sin(x))
hText = text('String','\{5\pi\div4, sin(5\pi\div4)\}\rightarrow',...
   'Position',[5*pi/4,sin(5*pi/4),0],...
   'HorizontalAlignment','right');
hMarker = line(5*pi/4,sin(5*pi/4),0,'Marker','*');

Create two more graphs without labels:

figure
x = pi/4:.1:9*pi/4;
plot(x,sin(x))
hAxes1 = gca;
figure
x = pi/2:.1:5*pi/2;
plot(x,sin(x))
hAxes2 = gca;

Copy the text and marker (hText and hMarker) to each graph by parenting them to the respective axes. Return the new handles for the text and marker copies:

newHandles1 = copyobj([hText,hMarker],hAxes1);
newHandles2 = copyobj([hText,hMarker],hAxes2);

Because the objective is to copy both objects to each axes, call copyobj twice, each time with a single destination axes.

Copy Multiple Objects to Multiple Destinations

When you call copyobj with multiple objects to copy and multiple parent destinations, copyobj copies respective objects to respective parents. That is, if h and p are handle arrays of length n, then this call to copyobj:

copyobj(h,p)

results in an element-by-element copy:

h(1) -> p(1);
h(2) -> p(2);
...
h(n) -> p(n);