MATLAB: Classes within classes: How to instantiate object without having its inner class object share memory

class methodsoop

SUMMARY : the 'main_class' contains two properties, 1) a single variable property 'x', and 2) a class property 'table_class', which contains only a single property value 'r'.
PROBLEM : Any object instances of the class 'main_class' will have independent values for the 'x' property (each has its own 'x' value), but continues to share the information/memory corresponding to the 'table_class' property (each instance has the same 'table_class' information).
EXAMPLE : 'a' is created as an instance of the 'main_class' and has the values [1 1 1] set to be the 'table' value. Then 'b' is created similarly except that the 'table' value is set to [2 2 2]. Now going back and checking the 'table' value for 'a' we see that it has also been changed to [2 2 2] which is undesired.
How do I keep inner class information separated on a instance-by-instance case?
*main.m***
a = main_class([1 1 1]);
b = main_class([2 2 2]);
a.table.r
*main_class.m***
classdef main_class < handle
properties
x % one variable property
table = table_class(); % one class property
end
methods
function obj = main_class(N)
obj.table.init_table(N);
end
end
end
*table_class.m***
classdef table_class < handle
properties
r = [];
end
methods
function obj = init_table(obj, N)
obj.r = N;
end
end
end

Best Answer

See When matlab evaluates expressions in class definitions for the explanation of the behaviour you observe. In particular "After initialization, the values returned by these expressions are part of the class definition and are constant for all instances of the class. Each instance of the class uses the results of the initial evaluation of the expressions without reevaluation."
The workaround is simple, do not initialise table in the class definition but do it in the constructor:
classdef main_class < handle
properties
x;
table; %not initialised here
end
methods
function this = main_class(N)
this.table = table_class(); %initialised here
this.table.init_table(N);
end
end
end