Copy Objects in MATLAB
In MATLAB, there are two kinds of objects – handles and values. The value objects are ordinary MATLAB objects which behave normally to copy operations. It means that when a value object is copied, the new copies of that object are completely independent of the original one i.e., if the original’s value is changed, the copied object will not be changed with it. See the following implementation.
Example 1:
Matlab
% MATLAB Code obj1 = 23 %initial value object copy_obj = obj1 %copying obj1 obj1 = 31 %changing original obj1 copy_obj %displaying copied object |
Output:
As can be seen, the copied object remained the same even after changing the original object’s value.
Now, the second kind of MATLAB objects are the handle objects. These objects do not behave the same way towards the copying operation as the value objects do. Handle objects referred with the help of their handle variables therefore, any copy of handle objects refer to the same handle object.
Let us see the same in action. We will create a MATLAB class gfg which has a property address.
Example 2:
Matlab
% MATLAB code classdef gfg < handle properties address end methods function obj = gfg(val) if margin > 0 obj.address = val; end end end end |
Output:
Now, in a new script file, we will create an object for the same and assign it an address.
Example 3:
Matlab
% MATLAB code user1 = gfg( "www.w3wiki.net" ) |
Output:
Now, we will create a copy of the user1 object and then, will compare the values of both objects.
Example 4:
Matlab
% MATLAB code user1 = gfg( "www.w3wiki.net" ); % Copying the user1 object user2 = user1; % Displaying address of user2 user2.address % Updating address of user1 user1.address = "https://www.w3wiki.net" ; fprintf( "After updation..." ) % Displaying addresses of user1 and user2 user1.address user2.address |
Output:
As can be seen that the properties of the user2 object changed automatically because both user1 and user2 refer to the same handle object of class gfg.
Contact Us