Infinite recursion when saving a custom object
2 次查看(过去 30 天)
显示 更早的评论
I have a Parent and a Child object, and I need to store a reference to the Parent in the Child. It works, but I cannot seem to save the object because Matlab goes into an infinite loop.
Here is a working example:
classdef Parent
properties
Child = [];
Color = 'Red';
end
methods
function ret = get.Child(this)
% Returns a Child instance, with this Box as a parent
ret = Child(this);
end
end
end
classdef Child
properties
Parent = [];
end
methods
function this = Child(Parent)
% Initialize by saving a reference to the Parent
if exist('Parent' , 'var')
this.Parent = Parent;
end
end
function ParentColor(this)
% Display the parent's color
disp(['My Parent is ' this.Parent.Color])
end
end
end
% This works
P = Parent();
P.Child.ParentColor
% This goes into an infinite loop
save('D:\matlab_recursion\Box.mat', 'P')
When saving, Matlab starts looping between get.Child and and Child's initialization.
Any ideas on why this happens, and how I could solve it?
In real life, it would not be practical to just store the parent's Color property in the child because I need to access A LOT of properties and methods of the parent...
2 个评论
采纳的回答
Matt J
2021-12-3
编辑:Matt J
2021-12-3
It happens because save() does know that the parent and child properties are supposed to be references to one another. It tries to de-reference all the property values when saving.
Here is a remedy:
classdef Parent<handle %<----make this a handle class
properties
Child = [];
Color = 'Red';
end
methods
function obj = Parent
obj.Child=Child(obj); %<---create the child in the constructor
end
end
end
classdef Child
properties
Parent = [];
end
methods
function obj = Child(p)
% Initialize by saving a reference to the Parent
if nargin
obj.Parent = p;
end
end
function ParentColor(obj)
% Display the parent's color
disp(['My Parent is ' obj.Parent.Color])
end
end
end
3 个评论
Matt J
2021-12-3
编辑:Matt J
2021-12-3
Matlab has a copy-and-write system, meaning that if you create a structure like this in the Matlab workspace,
data=rand(512,512,512); % 1 GB of RAM
S.a=data;
S.b=data;
Matlab knows that S.a and S.b refer to the same data and so additional RAM is not allocated when the struct is created. (If you change even 1 element in either S.a or S.b, an additional 1-2 GB will be allocated). However, when you save S to a .mat file, the save() command is not smart enough to see that a and b are the same data. It just saves independent deep copies of both variables in the file, resulting in a file size of about 2 GB.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!