copy a dynamicprops object by value
4 次查看(过去 30 天)
显示 更早的评论
I've created a class that is a subclass of dynamicprops,
classdef myclass < dynamicprops
When I create an instance of this
c = myclass
and then copy this
d = c
then d and c refer to the same underlying object. Therefore, whenever I change a property of c, the corresponding property of d changes as well (because c and d really refer to the same thing).
Question 1. How can I make a "real" independent copy of c?
Question 2. Alternatively, can I adapt the class definition so that it will be copied "by value" and not "by reference" ?
Thanks for your help.
回答(1 个)
Tejas
2024-9-20
Hello Yvan,
The 'dynamicprops' class is a subclass of the 'handle' class. This means that when 'myclass' inherits from 'dynamicprops', one object is copied to another by reference.
To ensure objects are copied by value, consider the following workaround:
- Save the object to be copied into a MAT file. The procedure for doing this can be found in this documentation: https://www.mathworks.com/help/matlab/ref/save.html#:~:text=Save%20All%20Workspace%20Variables%20to%20MAT%2DFile
- Load the object from the MAT file and assign it to a new object. Refer to this documentation for instructions on loading data from a MAT file: https://www.mathworks.com/help/matlab/ref/load.html#:~:text=Load%20All%20Variables%20from%20MAT%2DFile
This approach will create an independent copy of the original object. This workaround can also be incorporated into the class definition of 'myclass' by creating a function that takes an object as an input, performs the above steps, and returns the new object.
Below is an example code snippet demonstrating how this can be achieved:
classdef myclass < dynamicprops
methods
function newObj = copy(obj)
save('temp.mat','obj');
matFile = load('temp.mat');
newObj = matFile.obj;
end
end
end
The following syntax can then be used to create an independent copy of an object:
d = c.copy();
Below is a screenshot of the expected output:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!