Construct an empty array of objects of a handle class
24 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
回答 (1 件)
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
Make sure you read https://www.mathworks.com/help/matlab/matlab_oop/initializing-arrays-of-handle-objects.html
"
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!