필터 지우기
필터 지우기

Construct an empty array of objects of a handle class

조회 수: 18 (최근 30일)
Ahmed Hossam
Ahmed Hossam 2017년 5월 10일
편집: Nathan Jessurun 2019년 11월 19일
Hi,
I'm trying to construct an empty array of objects made from an user-defined handle class (class_1). I'm trying to acheive this in another also user-defined handle class (class_2).
My approach was to define a property x in class_2 with type class_1 like so:
def class_2 < handle
...
properties
x Class_1
end
...
end
Afterwards in the methods of class_2 I implemented a for-loop and filled x with a number of objects like so:
for k = 1:100
x(k) = Class_1(...,...)
end
This worked! Now I remembered reading something about performance issues and pre-allocation, when it comes to extending the size of arrays in a loop.
Is it possible to initialize my array before actually filling each object?
Thanks for your help and support!

답변 (1개)

Nathan Jessurun
Nathan Jessurun 2019년 11월 19일
편집: Nathan Jessurun 2019년 11월 19일
If class_1 doesn't have any handles inside, you can simply do:
x(100, 1) = Class_1(args);
for k = 1:100
x(k).prop1 = prop1(k);
...
end
You lose many benefits of preallocation if you reconstruct a new class every loop, but you could also use
x(100, 1) = Class_1(args);
for k = 1:100
cur_args = function_of(k);
x(k) = Class_1(cur_args);
end
"
A(4,5) = InitHandleArray;
results in two calls to the class constructor. The first creates the object for array element A(4,5). The second creates a default object that MATLAB copies to all remaining empty array elements."
So, if Class_1 has a handle object inside (like a plot handle), all 100 elements of x will point to the same plot, unless you reconstruct each object inside the for loop (like the second initialization example).
You can also look at modifying the behavior of the 'copy' method, as shown in https://www.mathworks.com/help/matlab/matlab_oop/custom-copy-behavior.html

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by