How to initialize a vector of class handles?

2020-03-26 03:55发布

问题:

I have a handle-based class that I need to create a vector of. An easy method of doing this is to dynamically construct the vector in a for loop, but this causes mlint to complain about the changing vector size.

classdef HandleClass < handle
    ...
end

...

for i = 1:10
    foo(i) = HandleClass();
end

I'm suspicious of the resource-hit required to use this method to allocate large arrays of complicated objects.

A comment in a previous thread described a useful method to create a vector using the repmat function. However, @gnovice warned that doing that would create a vector of handles pointing to the same object. I have tested this and it appears to be the case.

Is there a trick that allows a vector of unique handle objects to be pre-allocated without the use of a for loop?


Solution Summary

The solution presented by SCFrench correctly allocates the memory for the creation of a vector of objects. Other solutions will create the vector, but will not allocate the memory.

foo(10) = HandleClass();

回答1:

foo(10) = HandleClass();

This will default fill foo(1) through foo(9).

Note that this only works if HandleClass's constructor works with no input arguments (that is, it can be default-constructed).



回答2:

Seems you can do this by a call to the empty method that is present in all non-abstract classes.

foo = HandleClass.empty(10,0);
for i = 1:10
    foo(i) = HandleClass();
end


回答3:

Having a default constructor the accepted answer is fine. Having no default constructor (HandleClass()) returns not enough input arguments) the best possibility I see is creating a cell first:

foo=cell(1,10);
for ix=1:10
    foo{ix}=HandleClass(ix)
end;
foo=[foo{:}];