Avoiding duplicating data when using SuperClass
I am developing a MATLAB OOP project for the first time. My parent class will have a very large matrix which the children(many) need to access. How can I prevent the children from duplicating the data ?
In pseudo code I require that,
classdef parent properties largeMatrix; end end classdef child < parent methods function obj = child(parent) Data.parent of this child = Share from parent end ... something = largeMatrix(n,m); end end p = parent; p.largeMatrix = rand(100); c1 = child(p); c2 = child(p);
Both children c1 and c2 should access same data created in the original rand(100), but should not be copying the largeMatrix as I need many children, and would like the program to be memory efficient. The largeMatrix will be read from a file.
PS: This is the first time I am posting in this forum, so do forgive me if I have posted it wrongly.
A class is just a data type, it does not hold any data. If you instantiate an object parent of the Parent class, and then an object child of the Child class, then by default child will not inherit any data from parent. You can copy the data from one object to another by using a copy constructor.
child = parent; % this copies the data in `parent` to `child`
However, in this case Matlab creates a copy of the data in parent.
You can avoid copying the data by using handle objects. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. For example,
classdef A < handle properties largeMatrix; % wrap your large data into a handle class end end classdef B properties data; end methods function obj = B(mydata) obj.data = mydata; end end end
Then in the main program you can assign
a = A(); a.largeMatrix = rand(100); b1 = B(a); b2 = B(a); b3 = b1; % can even do this % no copies of largeMatrix were made, because `a` is a handle object % accessing largeMatrix b1.data.largeMatrix b3.data.largeMatrix
MATLAB copies the array on write.
Suppose that your parent class is (no need to subclass a handle):
classdef parent properties largeMatrix; end end
and your child class is:
classdef child < parent methods function obj = child(parent) obj.largeMatrix = parent.largeMatrix; end end end
Now, let's create parent and assign a large matrix to its property largeMatrix:
p = parent; p.largeMatrix = rand(1e4); % 750 MB circa
Check out the jump in the memory:
Now, let's create a child and check that the data was referenced:
c = child(p); size(c.largeMatrix)
As you can see no jump in the memory:
Finally, let's make a simple change in the child's data:
c.largeMatrix(1) = 1;
As you can see, only on write the array is effectively copied:
To prevent writes on child.largeMatrix define the property in the parent class with attribute (Abstract = true) and in the child (SetAccess = immutable).