Borrar filtros
Borrar filtros

Construct an empty array of objects of a handle class

18 visualizaciones (últimos 30 días)
Ahmed Hossam
Ahmed Hossam el 10 de Mayo de 2017
Editada: Nathan Jessurun el 19 de Nov. de 2019
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!

Respuestas (1)

Nathan Jessurun
Nathan Jessurun el 19 de Nov. de 2019
Editada: Nathan Jessurun el 19 de Nov. de 2019
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

Categorías

Más información sobre Graphics Object Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by