Clear Filters
Clear Filters

Declaring a class variable within a class, and using it

10 views (last 30 days)
%% main code
for aa = 1:2
Aclass(aa) = A;
end
for aa = 1:2
Aclass(aa).Dosumthing(aa);
end
%% class A define
classdef A < handle
properties
Bclass = B
end
function Dosumthing(obj, inputs)
Bclass.varis = inputs;
end
end
%% class B define
classdef B < handle
properties
varis = 0;
end
end
The value of Aclass(2).Bclass.varis became 2 even before the value of the for statement variable aa reached 2 by setting the breakpoint. Why?
I want the class variables of Class A to be independent.

Accepted Answer

Abhishek
Abhishek on 5 Jul 2023
Edited: Abhishek on 5 Jul 2023
Hi se chss ,
As per my understanding I think that your problem is that the value of Aclass(2).Bclass.varis became 2 even before the value of the for statement variable aa reached 2.
In the code which you shared, the issue is that you assigned the same instance of class B to the BClass property of both Aclass(1) and Aclass(2). Because of this they refer to the same instance of class B, resulting in shared properties.
In order to maintain that class variables of class A are independent, you need to have separate instances of class B for each instance of class A. You can look into the following code to achieve this :
%% main code
for aa = 1:2
Aclass(aa) = A;
end
for aa = 1:2
Aclass(aa).Dosumthing(aa);
end
%% class A define
classdef A < handle
properties
Bclass
end
methods
function obj = A()
obj.Bclass = B(); % Create a new instance of class B for each instance of class A
end
function Dosumthing(obj, inputs)
obj.Bclass.varis = inputs;
end
end
end
%% class B define
classdef B < handle
properties
varis = 0;
end
end
In this updated code the constructor of class A is modified to create a new instance of class B for each instance of class A.
By making the changes as told above, class variable of class A will be independent.
You can refer following documentation page for constructor method :

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!