Matrix/Array of Objects vs. Class Constructor

Let say I have a class Foo
classdef Foo
function obj = Foo(x,y)
% constructor's body
end
end
If I want to preallocate spaces for a matrix of Foo objects
>> foos = Foo(3,4);
How is it different from creating one object with arguments x = 3, y = 4?
>> foo = Foo(3,4);
Note that if I avoid preallocation, Matlab will give me some warning due to speed optimization.
Thanks,

 採用された回答

Khanh
Khanh 2014 年 10 月 10 日
編集済み: Khanh 2014 年 10 月 10 日

0 投票

Thanks for your response, Sean. However, it turns out every (nonabstract) class has a static method called empty, which can be used to create empty array. It makes things much simpler. See details here .

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2014 年 9 月 30 日
編集済み: Sean de Wolski 2014 年 9 月 30 日

0 投票

It depends on how your class sizes obj:
classdef FooC
properties
x
end
methods
function obj = FooC(sz)
obj.x = 1;
obj = repmat(obj,sz);
end
end
end
Now
fc = FooC([3,4])
I don't particularly like this approach. I would typically recommend constructing it similar to how you would construct a distributed array or gpuArray using static methods. Consider this:
classdef FooC
properties
x
end
methods
function obj = FooC()
obj.x = 1;
end
end
methods(Static)
function obj = preallocate(sz)
obj = FooC();
obj = repmat(obj,sz);
end
end
end
Now FooC always returns a scalar object but FooC.preallocate will give you an sz object, compare:
fcscalar = FooC
fcmat = FooC.preallocate([3,4])

2 件のコメント

Khanh
Khanh 2014 年 10 月 1 日
What if the constructor of FooC takes some argument? Say,
function obj = FooC(x,y)
obj.x = x;
obj.y = y;
end
Then the preallocate has to be written as following
methods(Static)
function obj = preallocate(sz)
obj = FooC(dummy1,dummy2);
obj = repmat(obj,sz);
end
end
Is there anyway better than that?
Thanks,
Sean de Wolski
Sean de Wolski 2014 年 10 月 1 日
This is where varargin is your friend:
function preallocate(sz,varargin)
obj = FooC(varargin{:})
obj = repmat(obj,sz);
end

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangePerformance and Memory についてさらに検索

質問済み:

2014 年 9 月 30 日

編集済み:

2014 年 10 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by