Hello, my code is like this:
'ClassA.m'
classdef ClassA < handle
properties
t double = 0
end
end
'ClassB.m'
classdef ClassB < handle
properties
a ClassA = ClassA;
end
end
'TestFun.m'
clear all
test_num = 1e5;
tic
class_b(test_num,1) = ClassB;
initialization_a = 0;
if initialization_a
for ii=1:test_num
class_b(ii).a = ClassA;
end
end
toc
class_b(1).a.t = 1;
disp(class_b(2).a.t)
Here is the problem description:
Array 'b' (type ClassB,length 1e5) has a member 'a' (type ClassA), they're both handle class.
when initialize 'b', each b.a shares the same value because 'a' is a handle class.
for some reason, i want each b.a have independent value, so i have 2 ways:
1st way is change the classA type as value class,
from "classdef ClassA < handle" to "classdef ClassA"
this will take about 0.15s;
2nd way is enabled loop assignment 'initialization_a = 1' in 'testfun.m'
this will take about 0.70s.
My question is, if i want to use handle class 'a'(2nd way), can i have a faster way to initialize 'a' and have independent b.a value,
the loop assignment seems to be too slow, especially when classA has more member variables.
Thanks a lot.
1 Comment
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/500362-how-can-i-initialize-nested-handle-class-with-independent-values#comment_911323
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/500362-how-can-i-initialize-nested-handle-class-with-independent-values#comment_911323
Sign in to comment.