Because handles reference the object, copying a handle copies the handle to a new variable name,
but the handle still refers to the same object. For example, given that hobj1 is a handle object with
property Data:
hobj1.Data
ans =
8
Change the value of hobj1's Data property and the value of the copied object's Data property also
changes:
hobj1.Data = 5;
hobj2.Data
ans =
5
Because hobj2 and hobj1 are handles to the same object, changing the copy, hobj2, also changes
the data you access through handle hobj1:
hobj2.Data = 17;
hobj1.Data
ans =
17
Reassigning Handle Variables
Reassigning a handle variable produces the same result as reassigning any MATLAB variable. When
you create an object and assign it to hobj1:
hobj1 = HdClass(3.14);
hobj1 references the new object, not the same object referenced previously (and still referenced by
hobj2).
Clearing Handle Variables
When you clear a handle from the workspace, MATLAB removes the variable, but does not remove
the object referenced by the other handle. However, if there are no references to an object, MATLAB
destroys the object.
Given hobj1 and hobj2, which both reference the same object, you can clear either handle without
affecting the object:
hobj1.Data = 2^8;
clear hobj1
hobj2
hobj2 =
HdClass with properties:
Data: 256
16 Using Objects
16-4
but the handle still refers to the same object. For example, given that hobj1 is a handle object with
property Data:
hobj1.Data
ans =
8
Change the value of hobj1's Data property and the value of the copied object's Data property also
changes:
hobj1.Data = 5;
hobj2.Data
ans =
5
Because hobj2 and hobj1 are handles to the same object, changing the copy, hobj2, also changes
the data you access through handle hobj1:
hobj2.Data = 17;
hobj1.Data
ans =
17
Reassigning Handle Variables
Reassigning a handle variable produces the same result as reassigning any MATLAB variable. When
you create an object and assign it to hobj1:
hobj1 = HdClass(3.14);
hobj1 references the new object, not the same object referenced previously (and still referenced by
hobj2).
Clearing Handle Variables
When you clear a handle from the workspace, MATLAB removes the variable, but does not remove
the object referenced by the other handle. However, if there are no references to an object, MATLAB
destroys the object.
Given hobj1 and hobj2, which both reference the same object, you can clear either handle without
affecting the object:
hobj1.Data = 2^8;
clear hobj1
hobj2
hobj2 =
HdClass with properties:
Data: 256
16 Using Objects
16-4
