cell array of classes
9 次查看(过去 30 天)
显示 更早的评论
Hi,
Consider a simple class Aclass:
classdef Aclass
properties
w
end
methods
function a = Aclass(b)
a.w = b;
end
end
end
The only data member is a vector. Now say I have a very large matrix that I'd like to turn into a cell array of Aclass objects:
n = 60000; k = 20;
l = zeros(n,k);
% Convert to a cell array of Aclass objects,
sz = size(l,1);
l2 = mat2cell(l,ones(1,sz),k);
l2 = reshape(cellfun(@Aclass,l2,'UniformOutput',0),[sz 1]);
Here, the matrix l with n rows is converted into a cell array with n members, each of which is an Aclass.
My question is: is this the best way to do this? The problem is that it's quite slow when n becomes large. Is there a way to make a "custom" constructor that would return a cell array of Aclass rapidly, perhaps using a MEX file?
Many thanks,
JLT
0 个评论
采纳的回答
per isakson
2012-1-13
R2010b doc says:
Building Arrays in the Constructor
A constructor function can return an object array by making the necessary assignments when initializing the output argument. ...
0 个评论
更多回答(1 个)
David Young
2012-1-13
Is there any reason to use a cell array rather than an array of Aclass objects? The latter should be more efficient in both time and storage.
You can make such an array in various ways, but probably the neatest is to provide the functionality in the class constructor. Per isakson's link gives the framework. Here's what it might look like for your case:
classdef Aclass
properties
w
end
methods
function a = Aclass(b)
if nargin > 0
a(size(b,1)) = Aclass; % preallocate array
for k = 1:size(b,1)
a(k).w = b(k,:);
end
end
end
end
end
and to create the array you simply do
arr = Aclass(l);
I think this goes faster than your cell-based code, but I haven't checked very carefully.
9 个评论
David Young
2012-1-17
In fact, it looks like get.w does not work, but for a different reason.
There is no recursion, because within get.w a reference to a.w goes directly to the property. (Oddly enough, the documentation doesn't seem to say this for get methods, though it does say it for set methods. However, it has to be the case that recursion is avoided, or get methods just wouldn't be useful.)
The reason get.w fails is that it is called once for each element of the array, rather than being passed the whole array. (I don't understand the rationale for this.) What it boils down to is that it looks like you have to use an ordinary method like getw.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!